java中的super關(guān)鍵字是一個(gè)引用變量,用于引用直接父類對(duì)象。
每當(dāng)創(chuàng)建子類的實(shí)例時(shí),父類的實(shí)例被隱式創(chuàng)建,由super關(guān)鍵字引用變量引用。
java super關(guān)鍵字的用法如下:
super可以用來(lái)引用直接父類的實(shí)例變量。super可以用來(lái)調(diào)用直接父類方法。super()可以用于調(diào)用直接父類構(gòu)造函數(shù)。可以使用super關(guān)鍵字來(lái)訪問(wèn)父類的數(shù)據(jù)成員或字段。 如果父類和子類具有相同的字段,則使用super來(lái)指定為父類數(shù)據(jù)成員或字段。
class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";
void printColor() {
System.out.println(color);// prints color of Dog class
System.out.println(super.color);// prints color of Animal class
}
}
class TestSuper1 {
public static void main(String args[]) {
Dog d = new Dog();
d.printColor();
}
}
執(zhí)行上面代碼,輸出結(jié)果如下 -
black
white
在上面的例子中,Animal和Dog都有一個(gè)共同的屬性:color。 如果我們打印color屬性,它將默認(rèn)打印當(dāng)前類的顏色。 要訪問(wèn)父屬性,需要使用super關(guān)鍵字指定。
super關(guān)鍵字也可以用于調(diào)用父類方法。 如果子類包含與父類相同的方法,則應(yīng)使用super關(guān)鍵字指定父類的方法。 換句話說(shuō),如果方法被覆蓋就可以使用 super 關(guān)鍵字來(lái)指定父類方法。
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("eating bread...");
}
void bark() {
System.out.println("barking...");
}
void work() {
super.eat();
bark();
}
}
class TestSuper2 {
public static void main(String args[]) {
Dog d = new Dog();
d.work();
}
}
執(zhí)行上面代碼,輸出結(jié)果如下 -
black
white
在上面的例子中,Animal和Dog兩個(gè)類都有eat()方法,如果要調(diào)用Dog類中的eat()方法,它將默認(rèn)調(diào)用Dog類的eat()方法,因?yàn)楫?dāng)前類的優(yōu)先級(jí)比父類的高。
所以要調(diào)用父類方法,需要使用super關(guān)鍵字指定。
super關(guān)鍵字也可以用于調(diào)用父類構(gòu)造函數(shù)。下面來(lái)看一個(gè)簡(jiǎn)單的例子:
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("dog is created");
}
}
class TestSuper3 {
public static void main(String args[]) {
Dog d = new Dog();
}
}
注意:如果沒(méi)有使用
super()或this(),則super()在每個(gè)類構(gòu)造函數(shù)中由編譯器自動(dòng)添加。

我們知道,如果沒(méi)有構(gòu)造函數(shù),編譯器會(huì)自動(dòng)提供默認(rèn)構(gòu)造函數(shù)。 但是,它還添加了super()作為第一個(gè)語(yǔ)句。
下面是super關(guān)鍵字的另一個(gè)例子,這里super()由編譯器隱式提供。
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
System.out.println("dog is created");
}
}
class TestSuper4 {
public static void main(String args[]) {
Dog d = new Dog();
}
}
執(zhí)行上面代碼,輸出結(jié)果如下 -
animal is created
dog is created
下面來(lái)看看super關(guān)鍵字的實(shí)際用法。 在這里,Emp類繼承了Person類,所以Person的所有屬性都將默認(rèn)繼承到Emp。 要初始化所有的屬性,可使用子類的父類構(gòu)造函數(shù)。 這樣,我們重用了父類的構(gòu)造函數(shù)。
class Person {
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Emp extends Person {
float salary;
Emp(int id, String name, float salary) {
super(id, name);// reusing parent constructor
this.salary = salary;
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
class TestSuper5 {
public static void main(String[] args) {
Emp e1 = new Emp(1, "ankit", 45000f);
e1.display();
}
}
執(zhí)行上面代碼,輸出結(jié)果如下 -
1 ankit 45000