簡體   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