You can simply define a separate Subclass.print() method with the desired implementation. Static methods belong to a class, so each subclass can have its own implementation.
public class Subclass { public Subclass() {} public static String print() { System.out.println(Subclass.class.getSimpleName()); } public void main(String[] args) { Super.print(); Subclass.print(); } }
Please note that your code may be somewhat simplified - Super.class enough instead of new Super().getClass() .
Also note that static methods are not polymorphic - Super.print() and Subclass.print() will always call the method in the corresponding class. That is why they are attached to the class, and not to the object.
If you have a large class hierarchy, you can get a lot of duplicate code by implementing a separate static print() in each. Instead, you can define one non-static method to do the job:
public abstract class Super { public final String print() { System.out.println(this.getClass().getSimpleName()); } ... }
Note that this method does not even need to be polymorphic - this.getClass() will always return the actual token of the subclass.
Note that I declared Super as abstract - it is (almost always) good practice to follow the base classes.
source share