通過使用這種超級的情況是否有可能以這樣的方式通過接入提供商運營
this.super.a;
...其中a
是任何數據成員使用this
和super
一起在java中。試着上面的代碼給出unexpected token
錯誤。
是否有任何其他可能的方式實現this
和super
使用點運算符?
通過使用這種超級的情況是否有可能以這樣的方式通過接入提供商運營
this.super.a;
...其中a
是任何數據成員使用this
和super
一起在java中。試着上面的代碼給出unexpected token
錯誤。
是否有任何其他可能的方式實現this
和super
使用點運算符?
將this
和super
一起使用沒有任何方法和意義。當您使用super
時,您已經在this
。這樣做沒有實際的理由。
你可以使用super.a
如果a
被聲明爲受保護的成員字段,你可以說:
this.a
,或者如果你定義一個getter方法:
this.getA();
我誤解或誤解了這個問題嗎?問題是關於,使用這個和超級在一起。 –
我正在爲他想要完成的事情做更多的努力,反對他如何努力完成它。我不認爲這兩個答案都不正確。 –
在一個類super.a如果a是ap受監護人或父母的公共成員。當你想在一個構造函數/方法的類成員一個從參數賦值
首先在區分
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
。
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
在子類的構造函數調用父類的構造函數。 (因爲你可能已經知道了,這裏沒有詳細說明)。
System.out.println(noise);
作品,因爲noise
從動物類繼承。只要在超類中不是private
,它就會被子類繼承。
System.out.println(this.noise);
可行,因爲this.
用於引用自己類中的任何成員。寫作this.noise
與寫作noise
相同。
System.out.println(super.noise);
因爲noise
實際上來自超類 - Animal
。由於它已經被繼承爲Cat類,因此編寫super.noise
與編寫this.noise
相同。
System.out.println(this.super.noise);
在編譯期間會給你一個錯誤。語法錯誤。邏輯上,如果你寫this.super
,你的意圖可能試圖引用你的超類的成員。但是由於所有非私人成員都將被繼承,因此不需要編寫this.super.xxx
。只需使用this.xxx
即可。
除非構件處於超私有,你可以this.getXXX()
提供的超有該存取方法。
這是什麼構造應該做的?你爲什麼認爲使用'this.a'或'super.a'是不夠的? – Holger
@Anmol Thukral你明白'this'和'super'的意思嗎? – user3437460
@ user3437460是的,我知道這個和超級的意思, –