Why is it possible to get access to the static method of my super class from child instance?
public class Test {
public static void main(String[] args) {
new UtilImpl().fun();
new AbstractUtil() {}.fun();
}
static abstract class AbstractUtil {
public static void fun() {
System.out.println("Fun!");
}
}
static class UtilImpl extends AbstractUtil {
}
}
I can agree with access to the static method of parent class from an instance of the parent class. But if I instantiate a child class, it's weird to have access to the static context of the parent class.
PS
And what are advantages of calling the static method on instance?
In Java, it is allowed to call static methods with an instance variable. This is defined in JLS section 8.4.3.2, quoting:
A method that is declared static is called a class method.
A class method is always invoked without reference to a particular object.
In such a case, Java will actually discard the instance you used and call the static method.
Example 15.12.4.1-1 expresses this in the following way:
When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:
class Test1 { static void mountain() { System.out.println("Monadnock"); } static Test1 favorite(){ System.out.print("Mount "); return null; } public static void main(String[] args) { favorite().mountain(); } }
which prints:
Mount Monadnock
Here favorite() returns null, yet no NullPointerException is thrown.
It's called inheritance. A subclass inherits public
members of the parent class, including static
methods. The important thing is that the static
method is not bound to any instance. You could just do:
UtilImpl.fun();
AbstractUtil.fun();
As far as the compiler is concerned, it's the same thing. The only difference is that your code creates objects but these are not relevant to the way the methods are called (plus as @Dici said in the comments you should have also gotten a warning from the compiler).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With