Please consider the below code demonstrating inheritance and reflection :
/*Parent class*/
package basics;
public class Vehicle {
private void parentPrivateMethod() {
System.out.println("This is the child private method");
}
public void print() {
System.out.println("This is a Vehicle method");
}
public void overrideThisMethod() {
System.out.println("Parent method");
}
}
/*Child class*/
package basics;
public class Car extends Vehicle {
private void childPrivateMethod() {
System.out.println("This is the child private method");
}
public String returnCarName() {
return "Manza";
}
@Override
public void overrideThisMethod() {
//super.overrideThisMethod();/*NOTE THIS*/
System.out.println("Child method");
}
}
/*Tester class*/
package basics;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class NewTester {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InstantiationException
*/
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException {
// TODO Auto-generated method stub
Car carInstance = new Car();
/* Normal method invocation */
carInstance.overrideThisMethod();
/* Reflection method invocation */
Method whichMethod = Car.class.getSuperclass().getMethod(
"overrideThisMethod", null);
whichMethod.invoke(carInstance, null);
/* Work-around to call the superclass method */
Method superClassMethod = Car.class.getSuperclass().getMethod(
"overrideThisMethod", null);
superClassMethod.invoke(Car.class.getSuperclass().newInstance(), null);
}
}
The output(with 'NOTE THIS' part commented) is :
Child method
Child method
Parent method
In case, the 'NOTE THIS' part is un-commented, the superclass method will be invoked, giving an output :
Parent method
Child method
Parent method
Child method
Parent method
When an instance of Car is created, the constructor of Vehicle runs first. Hence, I believe, that an instance of Vehicle is created,too, whose reference the Car instance holds via 'super'.
Question : How can I invoke the superclass version of 'overrideThisMethod' without using the /* Work-around to call the superclass method */ ?
Am I overlooking something here/making wrong assumptions here?