多态的存在要有3个必要条件:
要有继承,要有方法重写,父类引用指向子类对象
public class Animal {
public void voice(){
System.out.println("woshidongwu!");
}
public static void testVoice(Animal c){
c.voice();
}
public static void main(String[] args) {
Animal a = new Cat();
testVoice(a); //控制台输出的是miaomiaomiao
Animal d = new Dog();
Dog d2 = (Dog) d;
d2.seedoor(); //控制台输出看门狗
Animal c = new Cat();
Dog d3 = (Dog) c;
d3.seedoor(); //运行时会报错,猫怎么会编程狗呢?
}
}
class Cat extends Animal{
public void voice(){
System.out.println("miaomiaomiao");
}
}
class Dog extends Animal{
public void voice(){
System.out.println("wangwangwang");
}
public void seedoor(){
System.out.println("kanmengou");
}
}