package main.java.com.sf.part05.oop_05; public class Animal { int num = 10; public void eat() { System.out.println("动物吃食物"); } } class Dog extends Animal { public void protectedHome() { System.out.println("狗看家"); } int num = 20; @Override public void eat() { System.out.println("狗吃骨头"); } } class Cat extends Animal { int num = 30; @Override public void eat() { System.out.println("猫吃鱼"); } } class AnimalTest { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); Cat cat = new Cat(); cat.eat(); // 多态的形式 //父类的引用指向了子类的对象 // 父类/父接口 = new 子类(); // 多态的方式调用方法 编译看左边,运行看右边 // 多态调用属性/变量时,编译看左边,运行看左边 Animal animal = new Dog(); Animal animal1 = new Cat(); animal.eat(); int num = animal.num; // 强转 父类 - > 子类 // instanceof 判断当前变量是否属于某种类型 if(animal instanceof Dog){ Dog dog1 = (Dog) animal; dog1.protectedHome(); } System.out.println(num); animal1.eat(); } }