声明最终的静态方法是一个坏主意吗? [英] Is it a bad idea to declare a final static method?
问题描述
我理解在此代码中:
class Foo {
public static void method() {
System.out.println("in Foo");
}
}
class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
.. Bar
'隐藏'在 Foo
中声明的静态方法,而不是在多态意义上覆盖它。
.. the static method in Bar
'hides' the static method declared in Foo
, as opposed to overriding it in the polymorphism sense.
class Test {
public static void main(String[] args) {
Foo.method();
Bar.method();
}
}
...将输出:
在Foo
in Bar
in Foo
in Bar
在 Foo
中重新定义方法()
为 final
将禁用 Bar
隐藏它的功能,并重新运行 main()
将输出:
Re-defining method()
as final
in Foo
will disable the ability for Bar
to hide it, and re-running main()
will output:
Foo中的
in Foo
in Foo
(编辑:将方法标记为 final
时编译失败,并且仅在我删除 Bar.method()
)
(Edit: Compilation fails when you mark the method as final
, and only runs again when I remove Bar.method()
)
将静态方法声明为 final认为是不好的做法
,如果它有意或无意地重新定义方法而停止子类?
Is it considered bad practice to declare static methods as final
, if it stops subclasses from intentionally or inadvertantly re-defining the method?
(这个很好地解释了使用 final
的行为是什么......)
(this is a good explanation of what the behaviour of using final
is..)
推荐答案
我不认为将静态
方法标记为 final
。
I don't consider it's bad practice to mark a static
method as final
.
正如您所知, final
将阻止该方法被子类隐藏这是非常好的消息imho 。
As you found out, final
will prevent the method from being hidden by subclasses which is very good news imho.
我对您的陈述感到非常惊讶:
I'm quite surprised by your statement:
在Foo中重新定义method()作为final将禁用Bar隐藏它的能力,并重新运行main()将输出:
Re-defining method() as final in Foo will disable the ability for Bar to hide it, and re-running main() will output:
Foo中的
in Foo
in Foo
否,将方法标记为 Foo
中的> final 将阻止编译 Bar
。至少在Eclipse中我得到:
No, marking the method as final
in Foo
will prevent Bar
from compiling. At least in Eclipse I'm getting:
线程main中的异常java.lang.Error:未解决的编译问题:无法覆盖来自Foo的最终方法
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot override the final method from Foo
另外,我认为人们应该总是调用 static
方法即使在类本身内也使用类名限定它们:
Also, I think people should always invoke static
method qualifying them with the class name even within the class itself:
class Foo
{
private static final void foo()
{
System.out.println("hollywood!");
}
public Foo()
{
foo(); // both compile
Foo.foo(); // but I prefer this one
}
}
这篇关于声明最终的静态方法是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!