繁体   English   中英

不使用 super 访问超类属性

[英]Access super class property without using super

我只是在阅读 Java 基础知识,遇到了无法找到正确答案的情况。 java中的super关键字用于访问父类属性。 所以我的问题是,如果我们不允许访问 super 关键字,那么我们是否可以访问父类属性?

让我们举个例子来理解: 在下面的程序中,我们在子类中声明了一个数据成员 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();  
    }
}

输出:110

访问父类的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();  
   }
}

输出:100 如您所见,我们使用 super.num 访问了父类的 num 变量。

暂无
暂无

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

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