Subclassing from static methods

I think there may be no way to do this, but I thought it was worth asking. I want to do something like the following:

public class Super { public static String print() { System.out.println(new Super().getClass().getSimpleName()); } public Super() {} } public class Subclass extends Super { public Subclass() {} public void main(String[] args) { Super.print(); Subclass.print(); } } 

I hope that Super.print () will show "Super" and Subclass.print () to show "Subclass". However, I do not see how to do this from a static context. Thanks for the help.

I am well aware that I can do this without static methods, and that I can pass a class to every method call. I do not want to do this, as this requires overriding several static methods in many subclasses.

+4
source share
2 answers

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.

+9
source

You can do this without using static methods.

 public class Parent { public print(){ System.err.println(this.getSimpleName()); } } public class Child extends Parent { public void main(String[] args) { Parent p = new Parent(); p.print(); Child c = new Child(); c.print(); } } 
0
source

Source: https://habr.com/ru/post/1314331/


All Articles