Lets say I have a class called SuperClass:
public class SuperClass
{
protected void TheCake()
{
System.out.println("The cake is a lie");
}
}
and another called SubClass:
public class SubClass extends SuperClass
{
@Override
protected void TheCake()
{
System.out.println("The cake is not a lie");
}
}
In a third class I have this method
public void GetCake(SuperClass someObject)
{
Class clazz = someObject.getClass();
Method method = clazz.getMethod("TheCake");
method.invoke(someObject, (Object[])null));
}
This would never work, because TheCake is protected. So if I change this line:
Method method = clazz.getMethod("TheCake");
to this:
Method method = clazz.getDeclaredMethod("TheCake");
It would only work if someObject was an instance of SuperClass, and fail if it was an instance of SubClass, because off course the method is declared in SuperClass.
But what if I did this instead?
public void GetCake(SuperClass someObject)
{
Class clazz = SuperClass.class;
Method method = clazz.getDeclaredMethod("TheCake");
method.invoke(someObject, (Object[])null));
}
If someObject were an instance of SubClass, what method would be invoked? The SuperClass definition of the method or the SubClass override of the method?