super關(guān)鍵字

什么是super?

super代表的是當(dāng)前子類對(duì)象中的父類型特征。

什么時(shí)候使用super?

????????????子類和父類中都有某個(gè)數(shù)據(jù),例如,子類和父類中都有name這個(gè)屬性。如果要再子類中訪問父類中的name屬性,需要使用super。例1

????????????子類重寫了父類的某個(gè)方法(假設(shè)這個(gè)方法名叫m1),如果在子類中需要調(diào)用父類中的m1方法時(shí),需要使用super。例1

????????????子類調(diào)用父類中的構(gòu)造方法時(shí),需要使用super。


注意:super不能用在靜態(tài)方法中。

例1:

先定義一個(gè)Animal類

class Animal {

? ? public String name = "動(dòng)物";

? ? publicvoideat(){? ? ? ? ? ? ? ?

? ? ? ? System.out.println("吃飯");

? ? }

? ? publicvoidsleep(){? ? ? ? ? ?

? ? ? ? System.out.println("睡覺");

? ? }

}


定義一個(gè)Dog類繼承Animal


classDogextendsAnimal{

? ? public String name = "旺財(cái)";

? ? publicvoideat(){? ? ? ? ? ? ? ?

? ? ? ? System.out.println("吃狗糧");//狗喜歡吃狗糧? ? }

? ? publicvoidm1(){

? ? ? ? System.out.println(super.name);//調(diào)用父類中的name變量? ? ? ?

?????????????????System.out.println(this.name);//可以不加this,系統(tǒng)默認(rèn)調(diào)用子類自己的name? ? ? ??

????????????super.eat();//調(diào)用父類中的eat方法? ? ? ??

????????????this.eat();

? ? ? ? //eat();??

? }

}


測(cè)試類

public class AnimalTest01 {

? ? publicstaticvoidmain(String[] args){

? ? ? ? Dog d = new Dog();

? ? ? ? d.m1();

? ? }

}


例2:

class Animal {

? ? //顏色? ? String color;

? ? //品種? ? String category;

? ? publicAnimal(){

? ? ? ? System.out.println("Animal中的構(gòu)造方法");

? ? }

? ? publicAnimal(String color,String category){

? ? ? ? this.color = color;

? ? ? ? this.category = category;

? ? }

}class Dog extends Animal {

? ? publicDog(){

? ? ? ? super("土豪金","藏獒");//手動(dòng)調(diào)用父類中的有參構(gòu)造方法給成員變量進(jìn)行賦值? ? ? ? System.out.println("Dog中的構(gòu)造方法");

? ? }

}public class Test {

? ? publicstaticvoidmain(String[] args){

? ? ? ? Dog d = new Dog();

? ? ? ? System.out.println(d.color);

? ? ? ? System.out.println(d.category);

? ? }

}


注意:一個(gè)構(gòu)造方法第一行如果沒有this(…);也沒有顯示的去調(diào)用super(…);系統(tǒng)會(huì)默認(rèn)調(diào)用super();如果已經(jīng)有this了,那么就不會(huì)調(diào)用super了,super(…);的調(diào)用只能放在構(gòu)造方法的第一行,只是調(diào)用了父類中的構(gòu)造方法,但是并不會(huì)創(chuàng)建父類的對(duì)象。



super和this的對(duì)比

this和super分別代表什么

????????this:代表當(dāng)前對(duì)象的引用

????????super:代表的是當(dāng)前子類對(duì)象中的父類型特征

this和super的使用區(qū)別

????????調(diào)用成員變量

????????????????this.成員變量: 調(diào)用本類的成員變量

????????????????super.成員變量: 調(diào)用父類的成員變量

????????調(diào)用構(gòu)造方法

????????????????this(…) :調(diào)用本類的構(gòu)造方法

????????????????super(…):調(diào)用父類的構(gòu)造方法

????????調(diào)用成員方法

????????????????this.成員方法:調(diào)用本類的成員方法

????????????????super.成員方法:調(diào)用父類的成員方法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容