这里是父类引用指向一个子类对象(上转型对象),这是一种多态的体现,例如:public class Animal{
public void say(){
System.out.println("动物会叫");
}
}
class Dog extends Animal{
public void say(){
System.out.println("汪汪汪~~");
}
}
class Snake extends Animal{
public void say(){
System.out.println("嘶嘶嘶~~");
}
}
class Test{
public void test(Animal animal){
animal.say();
}
public static void main(){
new Test().test(new Animal());//输出动物会叫
//new Test().test(new Dog());//多态,输出汪汪汪
//new Test().test(new Snake());//多态,输出嘶嘶嘶
}
}还有就是接口回调:public interface Animal{
void say();
}
class Dog implements Animal{
public void say(){
System.out.println("汪汪汪~~");
}
}
class Snake implements Animal{
public void say(){
System.out.println("嘶嘶嘶~~");
}
}
class Test{
public void test(Animal animal){
animal.say();
}
public static void main(){
new Test().test(new Dog());//多态,输出汪汪汪
new Test().test(new Snake());//多态,输出嘶嘶嘶
}
}