java 如何调用子类方法
调用子类方法的基本方式
在Java中,调用子类方法通常涉及继承和多态的概念。父类引用可以指向子类对象,但默认只能调用父类中声明的方法。要调用子类特有的方法,需通过类型转换或直接使用子类引用。
使用类型转换调用子类方法
若父类引用指向子类对象,需通过向下转型(Downcasting)转换为子类类型后调用子类特有方法。需确保父类引用实际指向目标子类对象,否则会抛出ClassCastException。

class Parent {}
class Child extends Parent {
void childMethod() {
System.out.println("子类方法");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Child(); // 父类引用指向子类对象
((Child) parent).childMethod(); // 向下转型后调用子类方法
}
}
直接通过子类引用调用
直接创建子类对象并调用其方法是最直接的方式,无需类型转换。
Child child = new Child();
child.childMethod(); // 直接调用子类方法
多态与方法重写
若子类重写了父类方法,即使通过父类引用调用,实际执行的也是子类重写后的方法(动态绑定)。

class Parent {
void commonMethod() {
System.out.println("父类方法");
}
}
class Child extends Parent {
@Override
void commonMethod() {
System.out.println("子类重写方法");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.commonMethod(); // 输出:子类重写方法
}
}
使用instanceof进行类型检查
在向下转型前,建议使用instanceof检查引用是否指向目标子类,避免运行时异常。
if (parent instanceof Child) {
((Child) parent).childMethod();
} else {
System.out.println("类型不匹配");
}
接口与实现类调用
类似原则适用于接口和实现类。通过接口引用调用实现类特有方法时,同样需要向下转型。
interface MyInterface {}
class MyClass implements MyInterface {
void specificMethod() {
System.out.println("实现类特有方法");
}
}
public class Main {
public static void main(String[] args) {
MyInterface obj = new MyClass();
((MyClass) obj).specificMethod();
}
}
通过以上方法,可以灵活调用子类或实现类的特有方法,同时确保类型安全。






