1.super
主要的功能是完成子类调用父类中的内容,也就是调用父类中的属性或方法
2.super
关键字的用法如下:
super
可以用来引用直接父类的实例变量。
public class TestSuper1 {
public static void main(String args[]) {
Dog d = new Dog();
d.printColor();
}
}
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
}
}
输出结果为
black
white
super
可以用来调用直接父类方法。
public class TestSuper2 {
public static void main(String args[]) {
Dog d = new Dog();
d.work();
}
}
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();
}
}
输出结果
eating...
barking...
super()
可以用于调用直接父类构造函数。
public class TestSuper3 {
public static void main(String args[]) {
Dog d = new Dog();
}
}
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("dog is created");
}
}
输出结果
animal is created
dog is created
注意:如果没有使用super()
或this()
,则super()
在每个类构造函数中由编译器自动添加。
(当一个子类实例化时,无论是否显式调用super()
或this()
,最终都会执行父类的构造函数。这是因为子类的构造函数通常需要初始化继承自父类的成员变量,并且在实例化子类时,必须确保父类的构造函数得到执行以完成父类对象的初始化工作。因此,即使没有显式调用super()
或this()
,父类构造函数内的语句最终仍然会被执行。super语句必须是子类构造函数中的第一条语句。)
3.super
与this
关键字的比较
super
关键字:我们可以通过super
关键字来实现对父类成员的访问,用来引用当前对象的父类。 this
关键字:指向自己的引用。
public class TestAnimalDogDemo {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eatTest();
}
}
class Animal {
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void eatTest() {
this.eat(); // this 调用自己的方法
super.eat(); // super 调用父类方法
}
}
结果如下
animal : eat
dog : eat
animal : eat
调用父类中带参数的构造函数
super(name, age);