“决赛” Java 中类的修饰符

发布于 2024-11-27 12:51:01 字数 701 浏览 0 评论 0原文

我有一个快速而简单的问题。我有一个习惯,就是把每节课都定为“最终课”,当然,除非它需要由另一节课来延长。

这是一个坏习惯吗?一个好习惯?这还重要吗? 我了解修饰符对类的影响。

预先非常感谢!

编辑: 这是一个示例代码。该类不会被任何其他类扩展。

public final class Application {

    /**
     * Starts the application.
     * 
     * @param arguments arguments provided from command-line
     */
    public static void main(String[] arguments) {
        LaunchUtilities util = new LaunchUtilities(new EventHandler());

        try {
            util.addListener(43594);
        } catch (IOException ioe) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, "Could not bind a port to a listener!", ioe);
        }

        util.start();
    }
}

I have a quick and simple question. I have a habit of making every class 'final' unless of course, it needs to be extended by another.

Is this a bad habit? A good habit? Does it even matter?
I understand the effect of the modifier to a class.

Thanks a lot in advance!

Edit:
Here is an example code. This class will not be extended by any other classes.

public final class Application {

    /**
     * Starts the application.
     * 
     * @param arguments arguments provided from command-line
     */
    public static void main(String[] arguments) {
        LaunchUtilities util = new LaunchUtilities(new EventHandler());

        try {
            util.addListener(43594);
        } catch (IOException ioe) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, "Could not bind a port to a listener!", ioe);
        }

        util.start();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

呆头 2024-12-04 12:51:01

程序员(甚至 Java 专家)对此持不同意见。

Josh Bloch 设计了 ​​Java Collections 库、java.Math、assert,并且是 Google 的首席 Java 架构师(或者在他们雇用 Gosling 之前),他的书《Effective Java》中有一节专门介绍了这个问题。我同意他的话:

<块引用>

第 17 项:继承的设计和文档,否则禁止

他指出,子类化不是为此设计的类通常会导致灾难。

此外,继承设计的成本很高。

  1. 它对您的类可以执行的操作设置了主要限制
  2. 您必须编写更多文档,以便子类作者知道该类如何在内部使用公共方法
  3. 您必须对其进行测试。这需要测试编写子类

您可以随时改变主意并使某些内容成为非最终版本。你不可能把曾经不是最终的东西变成最终的。

阅读《Effective Java》会让这个论点变得更有说服力。它还将使您成为一名更好的程序员。

Programmers (even Java gurus) disagree on this.

Josh Bloch, who designed the Java Collections library, java.Math, assert, and is chief java architect at Google (or was before they hired Gosling) has a section of his book "Effective Java" devoted to this issue. I go with what he has to say:

Item 17: Design and document for inheritance or else prohibit it

He points out that subclassing classes that were not designed for it often leads to disaster.

Furthermore, designing for inheritance is expensive.

  1. It puts major limits on what your class can do
  2. You have to write more documentation so that sub class authors know how public methods are used internally by the class
  3. You must test it. This requires testing writing subclasses

You can always change your mind and make something non-final. You cant make something final that use to be not final.

Read "Effective Java" it makes this argument much more compellingly. It will also make you a better programmer.

农村范ル 2024-12-04 12:51:01

我要说的是坏习惯,原因如下:

  • 您没有指定任何特定的需要使该类成为最终的。
  • 您违反了开放/封闭原则。类应该对扩展开放,但对修改关闭。
  • 最终的类可能很难使用模拟框架进行测试。

例如:

public static void main(String[] args) {
    final Fruit mockFruit = Mockito.mock(Fruit.class);
}

private static final class Fruit {

}

...将产生...

Exception in thread "main" org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class org.foo.Foo$Fruit
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

当然,有一些有效的场景可以完成类。例如,您的课程是不可变的。

I'm going to say bad habit, for the following reasons:

  • You have not specified any particular need for the class to be final.
  • You are violating the open/closed principle. Classes should be open for extension, but closed for modification.
  • Finalized classes can be difficult to test with mocking frameworks.

For example:

public static void main(String[] args) {
    final Fruit mockFruit = Mockito.mock(Fruit.class);
}

private static final class Fruit {

}

...will yield...

Exception in thread "main" org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class org.foo.Foo$Fruit
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

Of course, there are valid scenarios for finalizing classes. For example, your class is immutable.

伴我心暖 2024-12-04 12:51:01

这是一个好习惯。将 Final 类更改为非 Final 类不应破坏任何代码。将非 Final 类更改为 Final 可能会破坏某些代码。

It is a good habit. Changing a final class to nonfinal should not break any code. Changing a nonfinal class to final may break some code.

静待花开 2024-12-04 12:51:01

我想说这是一个坏习惯,因为这意味着你在做决定时没有经过深思熟虑。不将事情定为最终的要点是,您可以子类化并进行更改,而无需更改原始代码。你正在破坏这个。

I would say it's a bad habit, because it means you're not thinking through the decision. The point of not making things final is that you can subclass and make changes without changing the original code. You're breaking this.

雾里花 2024-12-04 12:51:01

你的问题没有准确的答案。这取决于您编写课程的目的是什么。有些本质上应该是最终的,而另一些则不应该,除非您想明确禁止子类化。

如果您只是自己编程,那么我认为这不会有任何区别,每次您知道或需要子类化某些内容时,您都会删除 final 修饰符。

总之,类的 final 修饰符通常是向其他人暗示如何使用你的类,而不是真正的好/坏习惯。

Your question does not have a precise answer. It depends what is the purpose of the classes you are writing. Some should be inherently final while others shouldn't, except you want explicitly to forbid subclassing.

If you are programming just by yourself, then I don't think this would make any difference, you would remove the final modifier everytime you know or you need to subclass something.

In conclusion final modifier for a class it's usually a hint to someone else about how your class should be used, not a real good/bad habit.

回忆凄美了谁 2024-12-04 12:51:01

它对 HotSpot 没有影响,但我不确定其他运行时系统。我从来不用它,因为它似乎没什么用。虽然变量中的final(在HotSpot中也没有效果)可以阻止您更改您不想更改的值,但对于类,您确实不必担心。

不过,它曾经在 HotSpot 中很重要。对于 Android 和 Dalvik 之类的东西来说,这可能很重要。

It has no effect with HotSpot, but I am unsure about other run time systems. I never use it, because it seems to be useless. Whereas final in a variable (that also has no effect in HotSpot) can prevent you from changing a value you don't want to, you really don't have the same worries with a class.

It used to matter in HotSpot, though. And it may matter for something like Android and Dalvik.

鸵鸟症 2024-12-04 12:51:01

一般来说,这不是一个好主意。如果课程仅限于您的项目,那么可以这样做。当你发现需要扩展某些课程时,他总是可以将它们设为非最终课程。

In general this is not a good idea. If the classes are limited to your project it is okay to do this. When you see the need to extend some of the classes he can always make them non-final.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文