简体   繁体   中英

Access super class property without using super

I am just reading about java basics and came through a situation where I am not able to find a correct answer. In java super keyword in java is used to access parent class property. So my question is if we are not allow to access super keyword, is there anyway we can access parent class property?

Lets take an example to understand this: In the following program, we have a data member num declared in the child class, the member with the same name is already present in the parent class.* There is no way you can access the num variable of parent class without using super keyword. *.


//Parent class or Superclass or base class
class Superclass
{
   int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
   /* The same variable num is declared in the Subclass
    * which is already present in the Superclass
    */
    int num = 110;
    void printNumber(){
    System.out.println(num);
    }
    public static void main(String args[]){
    Subclass obj= new Subclass();
    obj.printNumber();  
    }
}

Output: 110

Accessing the num variable of parent class: By calling a variable like this, we can access the variable of parent class if both the classes (parent and child) have same variable.

super.variable_name Let's take the same example that we have seen above, this time in print statement we are passing super.num instead of num.

class Superclass
{
   int num = 100;
}
class Subclass extends Superclass
{
   int num = 110;
   void printNumber(){
    /* Note that instead of writing num we are
     * writing super.num in the print statement
     * this refers to the num variable of Superclass
     */
    System.out.println(super.num);
   }
   public static void main(String args[]){
    Subclass obj= new Subclass();
    obj.printNumber();  
   }
}

Output: 100 As you can see by using super.num we accessed the num variable of parent class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM