I have a parent, and a child class,
class Parent
{
// variables
// constructor
}
class Child extends Parent
{
// variables
// constructor
public void AChildMethod()
{
// do something
}
}
And inside my program, I have a reference of the main type, but it references to a child type
Parent obj = new Child();
Is it possible to call the “AChildMethod” method of the child in a way like this?
obj.AChildMethod();
Thank you very much in advance.
You can check whether it really is an instance of the Child class, and then simply cast to the child type:
However, if a cast like this is needed, it could be an indication that your class hierarchy should be improved.