一、基础概念
1.多态的定义: 允许不同类的对象对同一消息做出响应,同一消息可以根据发送对象的不同而采用多种不同的行为方式。
2.实现多态的必要条件:继承、重写、向上转型。(向上转型:在多态中需要将子类的引用赋给父类对象,只有这样该引用才能够具备技能调用父类的方法
和子类的方法)。
二、实现
两种实现形式:继承和接口。
(由于开发中更多的是使用接口,所以只展示接口示例)
interface Animal{
/**
*省略关键字abstract
*/
public void show();
}
class Bird implements Animal{
@Override
public void show(){
System.out.println("I am bird,i can fly");
}
}
class Tiger implements Animal{
@Override
public voidshow(){
System.out.println("I am Tiger,i eat birds");
}
}
public classTest{
public staticvoid main(String[]args){
Animal a = newBird();
a.show();
a = new Tiger();
a.show();
}
}
运行结果
E:\JavaWebDemo>javac Test.java
E:\JavaWebDemo>java Test
I am bird,i can fly
I am Tiger,i eat birds
E:\JavaWebDemo>java Test
I am bird,i can fly
I am Tiger,i eat birds
对象转型说明:
向上转型(安全): 子类对象转父类对象
向下转型(不安全):父类对象转子类对象
向下转型不安全示例:
public classTest{
public staticvoid main(String[]args){
Animal a = newBird();
/**
*向下转型安全
*/
Bird bird = (Bird)a;
a.show();
/**
*不安全
*/
Tiger tiger = (Tiger)a;
tiger.show();
}
}
运行:
E:\JavaWebDemo>javac -encoding utf-8 Test.java
E:\JavaWebDemo>java Test
I am bird,i can fly
Exception in thread "main" java.lang.ClassCastException: Bird cannot be cast to Tiger
at Test.main(Test.java:33)
E:\JavaWebDemo>java Test
I am bird,i can fly
Exception in thread "main" java.lang.ClassCastException: Bird cannot be cast to Tiger
at Test.main(Test.java:33)