What to do with static method overrides?
For example,
public class A {
public static int f() { return 1; }
}
public class B extends A {
public static long f() { return 100L; }
}
Unfortunately B.f()
couldn't be compiled because B.f()
tries to override A.f()
, and so the name clashes because the retur开发者_开发知识库n types aren't compatible.
I'm weired what's purpose to override a static method? Any use case? Can I just hide away A.f()
in class B?
Actual usage:
class EntityDTO {
public static List<EntityDTO> marshal(Collection<? extends Entity> entities) {
...
}
}
class BookDTO extends EntityDTO {
public static List<BookDTO> marshal(Collection<? extends Book> books) {
...
}
}
Strictly speaking, static methods can not be overridden. Method overriding is exclusively a feature of object polymorphism, and static methods doesn't belong to any object but the class itself.
Having clarified that, you should not make any of your methods static
. That would solve your problem in hand, at least. As the method arguments are different, it will not be considered as overriding, but overloading.
static methods are not overriden...But it is called method hiding. The benefits of using the same method name and parameters are just like any other method overriding benefits
static method can not be overridden.
Notice: your B.f()
should return int rather than long to pass compile.
I can't think of a use case where overriding static functions (in Java) can be useful, but if you ever absolutely must achieve it, here's how:
import java.lang.reflect.Method;
class A {
public static void callOut() {
System.out.println("A.callOut");
}
}
public class B extends A {
public static void callOut() {
System.out.println("B.callOut");
}
public static void main(String[] args) throws Exception
{
A a = new A();
A b = new B();
Method aM = a.getClass().getMethod("callOut");
Method bM = b.getClass().getMethod("callOut");
aM.invoke(null); // prints A.callOut
bM.invoke(null); // prints B.callOut
}
}
Maybe you need to rethink you design, if you have a need to override the marshal method, then it shouldn't be static in the first place.
精彩评论