mardi 30 juin 2015

How to access members of child class by using reference of parent class?

Let there are classes:

class Parent {
     public Parent getParent() {
         ...
     }
}

class Child extends Parent{
     public Parent getChild() {
         ...
     }
}

//instantiating Child by using reference of Parent
Parent parent = new Child();

when I use:

//Works fine
Parent parentObject = parent.getParent();

When I use:

//Doesn't works
Child childObject = parent.getChild();

But when type cast object:

//Works fine
Child childObejct = ((Child)parent).getChild();

being as programmer this is something hectic to type cast explicitly for every call where I wanted to use child members by reference of parent class.

Aucun commentaire:

Enregistrer un commentaire