In this answer there is this code:
//in a main method somewhere
Super instance = new Sub();
instance.method();
//...
public class Super {
public static void method() {
System.out.println("Super");
}
}
public class Sub extends Super {
public static void method() {
System.out.println("Sub");
}
}
This prints Super
as expected, but I have some code where given an instance, I would like to call the static Sub.method()
. One solution could be:
public class Sub extends Super {
public static void sMethod() {
Super.sMethod();
System.out.println("Sub (static)");
}
public void method() {
super.method();
System.out.println("Sub (instance)");
}
}
However, with non-trivial function bodies (in my case I am checking a parameter falls within limits allowed for the class) there is a lot of repeated code. Is there a good design pattern to resolve this? Reflection would work, perhaps, but it feels like a last resort.
Thinking a bit more, is this any better?
public class Sub extends Super {
public static void sMethod() {
Super.sMethod();
System.out.println("Sub (static)");
}
public void method() {
Sub.sMethod();
}
}