A Superclass Variable Can Reference a Subclass Object


A reference variable in a superclass A reference can be assigned to any subclass obtained from that superclass. This aspect of inheritance you will find quite effective in different situations. See the following example:

Program
class A
{
 int a,b;
 void Setab(int i, int j)
 {
  this.a=i;
  this.b=j;
 }
 void SumOfab()
 {
  int sum=a+b;
  System.out.println("Sum of a + b : "+sum);
 }
}
class B extends A
{
 int c,d;
 void Setcd(int i, int j)
 {
  this.c=i;
  this.d=j;
 }
 void SumOfcd()
 {
  int sum=c+d;
  System.out.println("Sum of c + d : "+sum);
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
    A a1=new A();
    B b1=new B();
    
    a1=b1;
    a1.Setab(10,20);
    a1.SumOfab();
    //a1.Setcd(30,40); //Error
    //a1.SumOfcd(); //Error
  }
}

It is important to understand that this is the type of reference variable. This is not the type of substance that is indicated. It determines which members can be accessed. This is when a reference to a subclass object is assigned to a reference variable in the superclass so you only have access to those parts of the object defined by the superclass.