简体   繁体   English

不使用 super 访问超类属性

[英]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.我只是在阅读 Java 基础知识,遇到了无法找到正确答案的情况。 In java super keyword in java is used to access parent class property. java中的super关键字用于访问父类属性。 So my question is if we are not allow to access super keyword, is there anyway we can access parent class property?所以我的问题是,如果我们不允许访问 super 关键字,那么我们是否可以访问父类属性?

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.让我们举个例子来理解: 在下面的程序中,我们在子类中声明了一个数据成员 num,同名成员已经存在于父类中。 * 无法访问 num 变量不使用 super 关键字的父类。 *. *.


//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输出: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.访问父类的num变量:通过这样调用一个变量,如果两个类(父类和子类)有相同的变量,我们就可以访问父类的变量。

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. super.variable_name 让我们以上面看到的相同例子为例,这次在打印语句中我们传递的是 super.num 而不是 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.输出:100 如您所见,我们使用 super.num 访问了父类的 num 变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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