在Java中,我们经常需要使用关键字"super"来调用父类的方法、属性和构造函数。这个关键字的使用非常重要,它可以帮助我们在子类中继承父类的内容,并且在必要的时候进行修改或扩展。下面我们来详细介绍如何在Java中使用"super"关键字。
1. 调用父类的构造函数
在子类的构造函数中,我们可以使用"super"关键字来调用父类的构造函数。这样做的目的是在创建子类对象时,先执行父类的构造函数,确保父类的成员变量被正确初始化。例如:
public class Parent {
private int num;
public Parent(int num) {
this.num = num;
}
public void printNum() {
System.out.println("Parent class: " + num);
}
}
public class Child extends Parent {
private int anotherNum;
public Child(int num, int anotherNum) {
super(num); // 调用父类的构造函数
this.anotherNum = anotherNum;
}
public void printAnotherNum() {
System.out.println("Child class: " + anotherNum);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(10, 20);
child.printNum(); // 输出:Parent class: 10
child.printAnotherNum(); // 输出:Child class: 20
}
}
2. 调用父类的方法
在子类中,我们可以使用"super"关键字来调用父类的方法。通过这种方式,我们可以在子类中改变父类方法的行为,或者在子类方法中添加新的逻辑代码。例如:
public class Parent {
public void printMessage() {
System.out.println("Parent class");
}
}
public class Child extends Parent {
public void printMessage() {
super.printMessage(); // 调用父类的printMessage方法
System.out.println("Child class");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printMessage(); // 输出:Parent class
// Child class
}
}
3. 调用父类的属性
在子类中,我们可以使用"super"关键字来访问父类的属性。这样做的目的是获取或修改父类的成员变量。例如:
public class Parent {
protected int num;
public Parent(int num) {
this.num = num;
}
}
public class Child extends Parent {
public Child(int num) {
super(num);
}
public void printNum() {
System.out.println("Parent class: " + super.num); // 访问父类的成员变量
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(10);
child.printNum(); // 输出:Parent class: 10
}
}
以上就是在Java中使用"super"关键字的方法和技巧。通过使用"super"关键字,我们可以更好地利用继承特性,扩展和重写父类的功能,实现更复杂的逻辑。掌握"super"关键字的正确使用方法,能够提高我们编写Java程序的效率和质量。


