When reference variable of parent class


Introduction

A reference variable of a parent class can be used to hold the address of an object of its child class. That is, a Parent type reference variable can refer to a child object and vice-versa.

What is the reference variable of the parent class?

The reference variable of parent class is a variable that is used to refer to a parent class object. It is declared using the extends keyword.

Why do we need it?

Parent class reference variable can be used to hold child class object. It is useful in situation where, a class is expected to work with objects of unknown classes. For example, the java.util.Vector class can take any type of object but all the objects should support the java.lang.Comparable interface so that the vector class can compare and sort them. If a program uses a Vector object to take and store objects of only one type, there is no problem, but when it needs to take any type of object, it becomes difficult because we need separate Vector objects to hold different type of objects i.e., we need one Vector object of Employee class, another Vector object of Student class etc. This problem can be solved by using parent class reference variable that can refer (hold) any type of child object i.e., an Employee as well as a Student and any other type too provided the child classes must inherit from a common parent class or they must implement a common interface that is supported by the parent reference variable.

How to use it?

It is used for accessing the members of a class from another class.

The reference variable of the parent class can be used to refer to the members of the child class, but not vice versa.

Examples


If you have a reference variable of a parent class type, you can point it to a child class object.
This is called upcasting.

Example:
In the following example, we have created a reference variable of type A and assigned an object of type B to it. This is possible because B is derived from A (B extends A).

class A { }
class B extends A { }

public class Test {
   public static void main(String[] args) {
      A a = new B();  // upcasting
   }
}</p><br /><h2>Conclusion</h2><br /><p>

In conclusion, a reference variable of a parent class can be used to refer to an object of a child class, but not the vice versa. In other words, an object of a child class can be assigned to a reference variable of parent class, but an object of parent class cannot be assigned to a reference variable of child class.


Leave a Reply

Your email address will not be published.