I understand that in this code:
class Foo {
public static void method() {
System.out.println("in Foo");
}
}
class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
.. 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();
}
}
...will output:
in Foo
in Bar
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
(Edit: Compilation fails when you mark the method as final
, and only runs again when I remove Bar.method()
)
Is it considered bad practice to declare static methods as final
, if it stops subclasses from intentionally or inadvertantly re-defining the method?
(this is a good explanation of what the behaviour of using final
is..)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…