Java-Superclass Variable Can Reference a Subclass Object

Superclass Variable Can Reference a Subclass Object

A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. In the following program, obj is a reference to NewData object, Since NewData is a subclass of Data, it is permissible to assign obj a reference to the NewData object. When a reference to a subclass object is assigned to a superclass reference variable, you will have access only to those parts of the object defined by the superclass. This is way obj can’t access data3 and data4 even it refers to a NewData object.

Program

1

Program Source

class Data {
    
    int data1;
    int data2;
}

class NewData extends Data{
    
    int data3;
    int data4;
}

public class Javaapp {

    public static void main(String[] args) {
        
        Data obj = new NewData();
        obj.data1 = 50;
        obj.data2 = 100;
        System.out.println("obj.data1 = "+obj.data1);
        System.out.println("obj.data2 = "+obj.data2);
    }
}

2 thoughts on “Java-Superclass Variable Can Reference a Subclass Object

Leave a Comment