在Java中,关键字"super"用于引用一个类的父类。它可以有以下几种用法:
1. 访问父类成员:通过使用"super"后跟一个点,你可以从子类中访问父类的成员(方法或字段)。当子类重写一个方法或隐藏一个字段时,通过使用"super"可以引用父类的版本。
2. 调用父类构造方法:在子类的构造方法中,可以使用"super"关键字调用父类的构造方法。这是为了使用父类构造方法初始化子类继承的成员。
以下是一个示例来说明这些用法:
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("动物正在发出声音");
}
}
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // 调用父类构造方法
this.breed = breed;
}
@Override
public void makeSound() {
super.makeSound(); // 调用父类方法
System.out.println("狗在叫");
}
public void display() {
System.out.println("名字: " + super.name); // 访问父类字段
System.out.println("品种: " + this.breed);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("巴迪", "拉布拉多");
dog.makeSound();
dog.display();
}
}
输出:
```
动物正在发出声音
狗在叫
名字: 巴迪
品种: 拉布拉多
```
在上面的示例中,类`Dog`继承了类`Animal`,并重写了`makeSound()`方法。在重写的方法中,使用`super`关键字调用了父类的`makeSound()`方法。还使用`super`关键字从子类的`display()`方法中访问了父类的`name`字段。最后,`super`关键字被用来在子类构造方法中调用父类的构造方法。
访问父类方法:
class Animal {
public void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
@Override
public void eat() {
super.eat(); // 调用父类的eat()方法
System.out.println("Dog is eating.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
输出:
Animal is eating.
Dog is eating.
在上面的示例中,子类Dog重写了父类Animal的eat()方法,并使用super.eat()调用了父类的eat()方法,然后在子类中添加了额外的输出。
调用父类构造方法:
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: " + name);
}
}
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // 调用父类的构造方法
this.breed = breed;
}
public void display() {
super.display(); // 调用父类的display()方法
System.out.println("Breed: " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", "Labrador");
dog.display();
}
}
输出:
Name: Buddy
Breed: Labrador
在上面的示例中,子类Dog有自己的构造方法,并使用super(name)调用了父类Animal的构造方法来初始化父类的实例变量。然后在子类的display()方法中,使用super.display()调用了父类的display()方法,并在子类中添加了额外的输出。
这些练习示例演示了super关键字在访问父类方法和调用父类构造方法时的用法。你可以根据这些示例进行练习和进一步尝试。
16万+

被折叠的 条评论
为什么被折叠?



