Even if static methods cannot be overridden, they are still inherited, so what you are trying to do will lead to a situation similar to
class Foo{ public static void m(Number n){ System.out.println("Number A"); }; public static int m(Number n){ System.out.println("Number B"); return 1; }; }
which is wrong, because you cannot have two methods with the same signature, but with different types of returned data. The reason this was forbidden is pretty simple ... Let's say we have methods:
Foo method(){ return new Foo(); }Bar method(){ return new Bar(); }
and you would like to call them like
System.out.println(method());
Should the result be Foo or Bar? The compiler will not be able to solve.
To prevent such situations, the compiler forbids overriding / hiding methods with the same signature by changing the types of returned data. The only exception is when you change the type of the return value to a more detailed one, for example
class X{ List<String> m(){...} } class Y extends X{ LinkedList<String> m(){...} }
So it seems that override not the best word here. The correct word should be hide , since static methods can be hidden, not overridden. But since the same rules check whether we can override / hide the method, the same error message is displayed in case of any problems that may be misleading.
Pshemo
source share