在Java中,子类调用父类方法主要有以下三种方式,具体使用场景和实现方式如下:
一、直接调用父类方法
子类可以直接调用父类中已定义的方法,无需额外操作。例如:
class Parent {
public void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
public void execute() {
display(); // 直接调用父类方法
}
}
二、通过super
关键字调用父类方法
当子类重写了父类方法时,可以使用super
关键字显式调用父类的原方法。例如:
class Parent {
public void add() {
System.out.println("Parent add");
}
}
class Child extends Parent {
@Override
public void add() {
super.add(); // 调用父类add方法
System.out.println("Child add");
}
}
注意 :super
调用必须出现在子类重写的方法内部,且调用父类构造方法时也需使用super
。
三、通过抽象类实现多态调用
抽象类中定义抽象方法,子类必须实现该方法。父类通过引用类型调用抽象方法时,实际执行的是子类重写的方法。例如:
abstract class Parent {
abstract void testMethod();
void callTest() {
testMethod(); // 多态调用
}
}
class Child extends Parent {
@Override
void testMethod() {
System.out.println("Child implementation");
}
}
使用示例 :
Parent parent = new Child();
parent.callTest(); // 输出: Child implementation
四、调用父类构造方法
子类构造方法中必须使用super
关键字调用父类构造方法,且调用顺序为先父类后子类。例如:
class Parent {
public Parent(String name) {
System.out.println("Parent constructor with name: " + name);
}
}
class Child extends Parent {
public Child() {
super("Dog"); // 调用父类构造方法
System.out.println("Child constructor");
}
}
总结
-
直接调用 :子类对象直接调用父类已定义的方法。
-
super
调用 :子类重写父类方法时,使用super
显式调用父类方法。 -
多态调用 :通过抽象类实现父类引用调用子类重写方法。
-
构造方法调用 :子类构造方法必须使用
super
调用父类构造方法。