A base class reference variable may be assigned the address of either a base class object or a derived class object.
True/False?
Can anybody show me an
If you have a superclass named Parent
public class Parent {
// ...
}
and a derived/subclass named Child
public class Child extends Parent {
// ...
}
then a base class reference refers to any variable defined as Parent pObj (here the name pObj doesn't matter), a base class object refers to an object created as new Parent() and a derived class object refers to one created as new Child().
So, the following
A base class reference variable may be assigned the address of either a base class object or a derived class object.
refers to an assignment like
Parent pObj = new Child();
What's the benefit of this you may ask? It's polymorphism. The subclass can override the superclass methods to redefine behaviour. This lets the pObj reference respond differently to the same method call depending on whether pObj points to a Parent() or a Child() object.
You may find it a bit difficult to grasp the benefits but take a look on Object-oriented programming esp. polymorphism and inheritance and your understanding will get better.