什么是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)用父類的成員方法