gpt4 book ai didi

java - 声明一个最终的静态方法是个坏主意吗?

转载 作者:IT老高 更新时间:2023-10-28 20:49:23 27 4
gpt4 key购买 nike

我明白在这段代码中:

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 中声明的静态方法,而不是在多态意义上覆盖它。

class Test {
public static void main(String[] args) {
Foo.method();
Bar.method();
}
}

...将输出:

in Foo
in Bar

重新定义 method()作为 finalFoo将禁用 Bar 的功能隐藏它,然后重新运行 main()将输出:

in Foo
in Foo

(编辑:将方法标记为 final 时编译失败,只有在我删除 Bar.method() 时才会再次运行)

将静态方法声明为 final 是否被认为是不好的做法? ,如果它阻止子类有意或无意地重新定义方法?

(this 很好地解释了使用 final 的行为是什么......)

最佳答案

我不认为将 static 方法标记为 final 是一种不好的做法。

如您所见,final 将防止该方法被子类隐藏恕我直言,这是个好消息

我对你的说法感到很惊讶:

Re-defining method() as final in Foo will disable the ability for Bar to hide it, and re-running main() will output:

in Foo
in Foo

不,在 Foo 中将方法标记为 final 会阻止 Bar 编译。至少在 Eclipse 中我得到了:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot override the final method from Foo

另外,我认为人们应该总是调用 static 方法,即使在类本身中也可以使用类名来限定他们:

class Foo
{
private static final void foo()
{
System.out.println("hollywood!");
}

public Foo()
{
foo(); // both compile
Foo.foo(); // but I prefer this one
}
}

关于java - 声明一个最终的静态方法是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1932399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com