2015-08-28 85 views
0

通過使用這種超級的情況是否有可能以這樣的方式通過接入提供商運營

this.super.a; 

...其中a是任何數據成員使用thissuper一起在java中。試着上面的代碼給出unexpected token錯誤。

是否有任何其他可能的方式實現thissuper使用點運算符?

+0

這是什麼構造應該做的?你爲什麼認爲使用'this.a'或'super.a'是不夠的? – Holger

+0

@Anmol Thukral你明白'this'和'super'的意思嗎? – user3437460

+0

@ user3437460是的,我知道這個和超級的意思, –

回答

0

thissuper一起使用沒有任何方法和意義。當您使用super時,您已經在this。這樣做沒有實際的理由。

你可以使用super.a

1

如果a被聲明爲受保護的成員字段,你可以說:

this.a

,或者如果你定義一個getter方法:

this.getA();

+0

我誤解或誤解了這個問題嗎?問題是關於,使用這個和超級在一起。 –

+0

我正在爲他想要完成的事情做更多的努力,反對他如何努力完成它。我不認爲這兩個答案都不正確。 –

0

在一個類super.a如果a是ap受監護人或父母的公共成員。當你想在一個構造函數/方法的類成員一個從參數賦值

0

使用所有的this

首先在區分

this.a使用,讓我們看看到的使用this。 我們不首先討論訪問修飾符(public/protected/private)。

class Cat 
{ 
    String furColor; 

    public Cat(){ 
     this("white"); //Using "this" to invoke its own constructor 
    } 
    public Cat(String furColor){ 
     this.furColor = furColor; //Using "this" to reference its own class member 
    } 
} 

this是對當前對象的引用。您可以使用this來引用當前對象中的任何成員。如果你不把課程擴展到其他課程,你不必擔心super關鍵字。 [所有類隱式擴展到類對象,但它不是這裏的問題]

使用super

下面,就讓我們一起來看看到super

class Animal 
{ 
    String noise; 
} 

class Cat extends Animal 
{ 
    String furColor; 

    public Cat(){ 
     this("white");    //Using "this" to invoke its own constructor 
    } 
    public Cat(String furColor){ 
     this.furColor = furColor; //Using "this" to reference its own class member 
     noise = "meow!";    //Set the noise for Cat 
    } 
    public void makeNoise(){ 
     System.out.println(noise);    //meow! 
     System.out.println(this.noise);  //meow! 
     System.out.println(super.noise);  //meow! 
     System.out.println(this.super.noise); //Error! 
    } 
} 

我們可以稱之爲super在子類的構造函數調用父類的構造函數。 (因爲你可能已經知道了,這裏沒有詳細說明)。

  1. System.out.println(noise);作品,因爲noise從動物類繼承。只要在超類中不是private,它就會被子類繼承。

  2. System.out.println(this.noise);可行,因爲this.用於引用自己類中的任何成員。寫作this.noise與寫作noise相同。

  3. System.out.println(super.noise);因爲noise實際上來自超類 - Animal。由於它已經被繼承爲Cat類,因此編寫super.noise與編寫this.noise相同。

  4. System.out.println(this.super.noise);在編譯期間會給你一個錯誤。語法錯誤。邏輯上,如果你寫this.super,你的意圖可能試圖引用你的超類的成員。但是由於所有非私人成員都將被繼承,因此不需要編寫this.super.xxx。只需使用this.xxx即可。

除非構件處於超私有,你可以this.getXXX()提供的超有該存取方法。