Java Base Class Reference Variable

后端 未结 2 795
执笔经年
执笔经年 2021-01-26 13:56

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-26 14:26

    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.

提交回复
热议问题