Java-Super Keyword

Super Keyword

In some cases, a variable in a subclass may have the same name as a super class variable. In such a case, the newly defined subclass variable hide the super class variable. In the following program, the super class Data has a variable named data1 and its value is 10. The subclass NewData also has a variable named data1 and its value is 20. In addition, this class inherits the variable data1 in the super class Data. Thus, the class NewData has two variables with the same name data1.

Within main( ) in the Javaapp, we create an object for the class NewData and then access the variable data1 through showData( ) method. As we know, this object has two variables with the same name data1. While the first one of these two variables has the value 10, the second variable has the value 20. Out of these two variables, the variable data1 that has come from the super class Data will be hidden. Therefore, the following program will display the value of the variable data1 that has been defined in the subclass NewData.

Program

When a variable in a subclass has the same name as a variable in the super class, the variable defined in the super class is hide. In some situations, we may wish to access the value of the hidden variable. We shall use the super keyword for accessing the value of a hidden variable, as illustrated in the following program.

Program

final2

Program Source

class Data {
    
    int data1 = 10;
}

class NewData extends Data{
    
    int data1 = 20;
    
    void showData()
    {
        System.out.println("NewData data1 = "+data1);
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        NewData obj = new NewData();
        obj.showData();
    }
}
class Data {
    
    int data1 = 10;
}

class NewData extends Data{
    
    int data1 = 20;
    
    void showData()
    {
        System.out.println("Data    data1 = "+super.data1);
        System.out.println("NewData data1 = "+data1);
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        NewData obj = new NewData();
        obj.showData();
    }
}

Leave a Comment