Java super 关键字
Java super 关键字
在 Java 中,super 关键字用于引用子类的父类。
super 关键字最常见的用途是消除具有同名方法的超类和子类之间的混淆。
它主要有两种用途:
- 访问父类的属性和方法
- 调用父类构造函数
访问父类方法
如果子类中有一个与其父类中同名的方法,您可以使用 super 来调用父类的方法:
示例
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void animalSound() {
super.animalSound(); // 调用父方法
System.out.println("The dog says: bow wow");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.animalSound();
}
}
输出:
The animal makes a sound
The dog says: bow wow
注意: 当您想要调用子类中已重写的父类方法时,请使用 super。
访问父类属性
如果父类和子类存在同名属性,您也可以使用 super 来访问父类的属性:
示例
class Animal {
String type = "Animal";
}
class Dog extends Animal {
String type = "Dog";
public void printType() {
System.out.println(super.type); // 访问父属性
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.printType();
}
}
输出:
Animal
调用父类构造函数
使用 super() 调用父类的 构造函数。这对于重用初始化代码尤其有用。
示例
class Animal {
Animal() {
System.out.println("Animal is created");
}
}
class Dog extends Animal {
Dog() {
super(); // 调用父构造函数
System.out.println("Dog is created");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
}
}
输出:
Animal is created
Dog is created
注意:对super()的调用必须是子类构造函数中的第一条语句。

