多态
对象在不同时刻表现出来的不同状态(对于引用类型,有两个状态:编译期状态、运行期状态)
实现多态的前提:需要存在继承或者实现关系;需要有方法重写;由父类引用指向子类对象
格式:父类 变量名=new 子类();
- class Animal
- {
- public Animal(){}
- public void show()
- {
- System.out.println("Animal show");
- }
- public void eat()
- {
- System.out.println("Animal eat");
- }
- }
- class Dog extends Animal
- {
- public void show()
- {
- System.out.println("Dog show");
- }
- public void eat()
- {
- System.out.println("Dog eat bone");
- }
- public void say()
- {
- System.out.println("I'm Dog");
- }
- }
- class Cat extends Animal
- {
- public void show()
- {
- System.out.println("Cat show");
- }
- public void eat()
- {
- System.out.println("Cat eat fish");
- }
- public void say()
- {
- System.out.println("I'm Cat");
- }
- }
- class AnimalTool
- {
- public static void print(Animal animal)
- {
- animal.show();
- animal.eat();
- }
- }
- class AnimalTest
- {
- public static void main(String[] args)
- {
- Animal a=new Dog();//向上转型
- Animal b=new Cat();//向上转型
- AnimalTool.print(a);
- AnimalTool.print(b);
- System.out.println("******************");
- Dog d=(Dog)a;//向下转型
- d.say();
- System.out.println("******************");
- Cat c=(Cat)b;//向下转型
- c.say();
- }
- }
复制代码 |