向上转型一定是安全的
// 抽象父类Animal
public abstract class Animal {
public abstract void eat();
}
// 子类Cat重写eat方法
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
// 向上转型一定是安全的,没有问题的,正确的,但是也有一个弊端
// 对象一旦向上转型为父类,那么久无法调用子类原本特有的内容(子类特有方法)
// 解决方案: 用对象的向下转型【还原】
public class Main {
public static void main(String[] args) {
//对象的向上转型,就是,父类引用指向子类对象。
Animal animal = new Cat();
animal.eat();
}
}
// Ctrl + O 快速重写父类方法
// 这是Animal的另一个Dog子类
public class Dog extends Animal{
@Override
public void eat() {
System.out.println("狗吃Shit");
}
public void watchHouse(){
System.out.println("狗看家");
}
}
/**
* 如何才能知道一个父类引用的对象,本来是什么子类?
*
* 格式:
*
* 对象 instanseof 类名称
*
* 这将会得到一个boolean值结果,也就是判断前面的对象能不能当做后面类型的实例。
*/
public class Instanseof {
public static void main(String[] args) {
Animal animal = new Cat() ;//向上转型,本来是一只猫
animal.eat(); // 猫吃鱼
// 希望调用子类特有方法,需要向下转型
// 判断一下父类引用animal本来是不是Dog
if(animal instanceof Dog){
Dog dog = (Dog) animal;
dog.watchHouse();
}
if(animal instanceof Cat){
Cat cat = (Cat) animal;
cat.catchMouse();
}
System.out.println("=======");
// 调用方法
// 宠物猫方法
giveMeAPetCat(new Cat());
System.out.println("=======");
// 宠物狗方法
giveMeAPetDog(new Dog());
}
// 宠物猫
public static void giveMeAPetCat(Animal animal){
if(animal instanceof Cat){
Cat cat = (Cat) animal;
cat.catchMouse();
}
if(animal instanceof Dog){
Dog dog = (Dog) animal;
dog.watchHouse();
}
}
// 宠物狗
public static void giveMeAPetDog(Animal animal){
if(animal instanceof Cat){
Cat cat = (Cat) animal;
cat.catchMouse();
}
if(animal instanceof Dog){
Dog dog = (Dog) animal;
dog.watchHouse();
}
}
}
原文:https://www.cnblogs.com/fenixG/p/12960682.html