Java的多态
与继承有关的多态性
与继承有关的多态性是指父类的某个实例方法被其子类重写时,可以各自产生自己的功能行为,即同一个操作被不同类型对象调用时可能产生不同的行为。
/*
* 父类
*/
class Animal{
void cry(){}
}
/*
* Dog是Animal的子类
*/
class Dog extends Animal{
void cry(){
System.out.println("汪汪");
}
}
/*
* Cat也是Animal的子类
*/
class Cat extends Animal{
void cry(){
System.out.println("喵喵");
}
}
public class Example{
public static void main(String args[]){
Animal animal;
animal=new Dog();//animal是Dog对象的上转型对象
animal.cry(); //输出 汪汪
animal=new Cat();//animal是Cat对象的上转型对象
animal.cry(); //输出 喵喵
}
}
与接口有关的多态性,也叫接口回调
接口回调是多态的另一种体现。接口回调是指:可以把实现某一接口的类创建的对象赋给该接口声明的接口变量,那么该接口变量就可以调用被类实现的接口中的方法,其实就是通知相应的对象调用重写的方法,这一过程称为接口回调。
/*
* 接口
*/
interface Animal{
void cry();
}
/*
* Dog实现Animal接口
*/
class Dog implements Animal{
public void cry(){
System.out.println("汪汪");
}
}
/*
* Cat实现Animal接口
*/
class Cat implements Animal{
public void cry(){
System.out.println("喵喵");
}
}
public class Example{
public static void main(String args[]){
Animal animal; //接口变量
animal=new Dog();//animal引用的是Dog对象
animal.cry(); //输出 汪汪
animal=new Cat();//animal引用的是Cat对象
animal.cry(); //输出 喵喵
}
}