(摘自头歌)
任务描述
掌握super
关键字的使用。
相关知识
1.super
关键字;2.super
关键字的使用;3.super
与this
关键字的比较。
super
关键字
super
主要的功能是完成子类调用父类中的内容,也就是调用父类中的属性或方法。
super
关键字的使用
super
关键字的用法如下:
super
可以用来引用直接父类的实例变量。super
可以用来调用直接父类方法。super()
可以用于调用直接父类构造函数。
1.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
在上面的例子中,Animal
和Dog
都有一个共同的属性:color
。 如果我们打印color
属性,它将默认打印当前类的颜色。要访问父属性,需要使用super
关键字指定。
2.通过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...
在上面的例子中,Animal
和Dog
两个类都有eat()
方法,如果要调用Dog
类中的eat()
方法,它将默认调用Dog
类的eat()
方法,因为当前类的优先级比父类的高。所以要调用父类方法,需要使用super
关键字指定。
3.使用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
关键字:我们可以通过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
上表对 this
与 super
的差别进行了比较,从上表中不难发现,用 super
或 this
调用构造方法时都需要放在首行,所以super
与 this
调用构造方法的操作是不能同时出现的