Java Base Class Reference Variable

后端 未结 2 751
执笔经年
执笔经年 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:10

    A base class reference variable may be assigned the address of either a base class object or a derived class object.

    True/False?

    True, because all derived class object is an instance of the base class, but not the other way round.

    Can anybody show me an example of what this means? I'm new to Java and am trying to understand language specific terms of Java. Thanks.

    First of all, you need to know what is a base class and a derived class.

    Base class also known as parent class or super class is a class which is extended by another. A simple example would be Animal class.

    While a child class extends from its super class. For example, Lion class.

    We know that all lions are animals. But not all animals are essentially lions. The subclass is just a subset of the superclass.

    Hence, when we have a base class reference, we are allowed to assign derived class object into it.

    Example:

    class Animal{
        
    }
    
    class Lion extends Animal{
    
    }
    
    
    Animal someAnimal = new Lion(); //because all lions are animals
    

    However, the reverse is untrue. Thus not possible and not allowed in Java:

    Lion lion = new Animal(); //not allowed in Java.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题