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
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.