Java-Superclass Reference to Subclass Reference

Superclass Reference to Subclass Reference

To create a conversion from superclass reference(that pointing to subclass object) to subclass reference, you must use a cast. A cast is simply an explicit type conversion.

Program

final

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;
        
        NewData nobj = (NewData)obj;
        nobj.data3 = 150;
        nobj.data4 = 200;
        System.out.println("nobj.data1 = "+nobj.data1);
        System.out.println("nobj.data2 = "+nobj.data2);
        System.out.println("nobj.data3 = "+nobj.data3);
        System.out.println("nobj.data4 = "+nobj.data4);
    }
}

Leave a Comment