// 定义一个父类 Animal
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
// 子类特有的方法
public void fetchStick() {
System.out.println("Fetching stick...");
}
}
public class Main {
public static void main(String[] args) {
// 创建一个 Dog 对象并将其赋值给 Animal 类型的引用
Animal myDog = new Dog();
// 将父类引用强制转换为子类
if (myDog instanceof Dog) {
Dog dog = (Dog) myDog;
dog.makeSound(); // 输出: Bark
dog.fetchStick(); // 输出: Fetching stick...
} else {
System.out.println("myDog is not an instance of Dog");
}
// 如果直接使用父类引用调用子类特有的方法,会报错
// myDog.fetchStick(); // 编译错误:找不到符号
}
}
Animal 父类和一个继承自 Animal 的 Dog 子类。Dog 类重写了 makeSound 方法,并添加了自己特有的方法 fetchStick。Dog 对象,并将其赋值给 Animal 类型的引用 myDog。fetchStick,我们需要将 myDog 强制转换为 Dog 类型。在进行强制转换之前,使用 instanceof 操作符确保 myDog 实际上是一个 Dog 对象,以避免 ClassCastException。Dog 类中的所有方法,包括从 Animal 继承的方法和 Dog 自己特有的方法。上一篇:java本地缓存
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站