I have 2 classes Class A & Class B where Class A extends Class B
Now in the constructor of Class A , I have
Class A(Integer integerParam){
B superclass = new B(integerParam);
}
and the constructor of Class B is as
Class B(Integer integerParam) {
System.out.println(integerParam);
}
In addition to this I have a few methods in Class B as follows
public void ClassBMethod(){
System.out.println(integerParam);
}
I want to use reflection to invoke the Super Class method ClassBMethod, and I create an Instance of the Super class to do so like this
Class superClazz = Class.forName(classInstance.getClass().getSuperclass().getName());
Constructor superClassconstructor = superClazz.getConstructor(new Class[]{Integer.class});
Object superclassInstance = superClassconstructor.newInstance(integerParam);
The problem is here the instance of the Super class is getting created twice, once through the Class A constructor and second on reflection.
How can I call the avoid this and call the Super class method without creating the instance
I’m not a 100% sure, but I think you might be wanting to do this…
In other words, if I understand correctly, you dont want the constructor to be called twice? You want to call the
classBMethod()on the already existing instance?Besides, the constructor for A looks pretty weird. Judging from the signature of the constructors, it feels at it would make most sense for the A constructor to be:
An explanation of this:
Lets compare the classes A and B to more concrete objects:
If you are doing the constructor:
You are essentialy saying that when you create an apple (
new Apple(someWeight);) that apple IS a fruit with weight == someWeight.If you are doing:
That means: when you are calling
new Apple(someWeight)you create a different fruitb(not the apple itself) which you give someWeight. So essentially what you have is an Apple with unspecified weight, and another unknown fruit which weighs someWeight. Since the other fruit is declared within the constructor, as soon as the constructor is finished, the other fruit will disappear. The only thing that will be left is an apple with unspecified weight (or with a default weight specified by the default constructor).