java父类如何调用子类的方法
在Java中,父类直接调用子类的方法通常需要通过多态或反射实现。以下是几种常见的方法:
通过多态实现
多态允许父类引用指向子类对象,从而调用子类重写的方法。这是最常见的方式。
class Parent {
void callMethod() {
System.out.println("Parent method");
}
}
class Child extends Parent {
@Override
void callMethod() {
System.out.println("Child method");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Child(); // 父类引用指向子类对象
parent.callMethod(); // 实际调用子类方法
}
}
通过反射实现
如果父类需要调用子类独有的方法(未在父类中定义),可以使用反射机制。
import java.lang.reflect.Method;
class Parent {
void callChildMethod(Object child) throws Exception {
Method method = child.getClass().getMethod("childMethod");
method.invoke(child);
}
}
class Child extends Parent {
public void childMethod() {
System.out.println("Child-specific method");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Parent parent = new Parent();
Child child = new Child();
parent.callChildMethod(child);
}
}
通过模板方法模式
父类定义抽象方法,子类实现具体逻辑。父类在模板方法中调用这些抽象方法。
abstract class Parent {
abstract void childMethod();
void templateMethod() {
childMethod(); // 调用子类实现
}
}
class Child extends Parent {
@Override
void childMethod() {
System.out.println("Child method implementation");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Child();
parent.templateMethod();
}
}
注意事项
- 多态方式要求子类方法必须重写父类方法。
- 反射方式会破坏封装性,且性能较低,应谨慎使用。
- 模板方法模式是更优雅的设计,适合固定流程中需要子类定制的情况。







