错误方法:
public class Main{
public static void main(String args[]){
Animal a = new Animal(); // Animal 对象
Animal b = new Dog(); // Dog 对象
a.move();// 执行 Animal 类的方法
b.move();//执行 Dog 类的方法
b.bark();
}
}
class Animal{
public void move(){
System.out.println("动物可以移动");
}
}
class Dog extends Animal{
public void move(){
System.out.println("狗可以跑和走");
}
public void bark(){
System.out.println("狗可以吠叫");
}
}
运行结果:
Main.java:9: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error
error: compilation failed
原因:
Animal b = new Dog();这句表现的是JAVA的多态,表示由一个父类的引用指向子类,因为是引用的是动物类型,而动物类没有getC()方法,所以编译器会认为,这个方法是不存在的。
如果要通过编译 必须这样写:Dog b = new Dog();
好比是:我说要一个动物,你给我一只小狗,这是可以的,但是狗会啃骨头,并不等于其他动物都会啃骨头。所以你给我一个动物,然后告诉我它要啃骨头,然而这只动物未必是小狗,所以我告诉你编译错误了
正确方法:
public class Main{
public static void main(String args[]){
Animal a = new Animal(); // Animal 对象
Dog b = new Dog(); // Dog 对象
a.move();// 执行 Animal 类的方法
b.move();//执行 Dog 类的方法
b.bark();
}
}
class Animal{
public void move(){
System.out.println("动物可以移动");
}
}
class Dog extends Animal{
public void move(){
System.out.println("狗可以跑和走");
}
public void bark(){
System.out.println("狗可以吠叫");
}
}
运行结果:
动物可以移动
狗可以跑和走
狗可以吠叫