Tuesday 8 January 2019

java - Why are class static methods inherited but not interface static methods?

Answer


Answer




I understand that in Java static methods are inherited just like instance methods, with the difference that when they are redeclared, the parent implementations are hidden rather than overridden. Fine, this makes sense. However, the Java tutorial notes that




Static methods in interfaces are never inherited.





Why? What's the difference between regular and interface static methods?



Let me clarify what I mean when I say static methods can be inherited:



class Animal {
public static void identify() {
System.out.println("This is an animal");
}
}
class Cat extends Animal {}


public static void main(String[] args) {
Animal.identify();
Cat.identify(); // This compiles, even though it is not redefined in Cat.
}


However,



interface Animal {

public static void identify() {
System.out.println("This is an animal");
}
}
class Cat implements Animal {}

public static void main(String[] args) {
Animal.identify();
Cat.identify(); // This does not compile, because interface static methods do not inherit. (Why?)
}


Answer



Here's my guess.



Since Cat can only extend one class if Cat extends Animal then Cat.identify has only one meaning. Cat can implement multiple interfaces each of which can have a static implementation. Therefore, the compiler would not know which one to choose?



However, as pointed out by the author,




Java already has this problem, with default methods. If two interfaces

declare default void identify(), which one is used? It's a compile
error, and you have to implement an overriding method (which could
just be Animal.super.identify()). So Java already resolves this
problem for default methods – why not for static methods?




If I was to guess again, I'd say that with default the implementation is part of Cat's vtable. With static it cannot be. The main function must bind to something. At compile time Cat.identify could be replaced with Animal.identify by the compiler but the code wouldn't match reality if Cat was recompiled but not the class that contains main.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...