I have the following classes.
public class Super{
public static void useSubClass(){
//I want to access the sub class object here, how.
}
}
public class Sub1 extends Super{
}
public class Sub2 extends Super{
}
I want to access the sub-class object from a static method in super-class. i.e. When I call Sub1.useSubClass() the method has access to Sub1.class and when I use Sub2.useSubClass(), I can access the Sub2.class.
Is there any way to access the sub-class object from super-class.
I figured something out. It works if implemented with care.
This is just a toy example. The super class contains a static class that contains a method to retrieve the calling class.
In the subclass I have another static method which calls the superclass’s method for printing the class name.
The
Mainclass/function contains two calls toSub‘s inherited and locally implemented method. The first call prints null, because the calling context (i.e. Main) is not a subclass ofSuperHowever the delegate method inSubworks because the calling context is now a subclass ofSuperClassand hence the calling class can be determined.