实验代码是关于多态的用法创建了两个抽象父类Animal类和Transport类Animal的子类中Bird类实现了飞翔接口Transport类中的Airport类实现了飞翔接口
多态
// 在容器的泛型中使用父类或接口,完成多态匹配
// 在遍历容器的方法中使用父类或接口作为参数,完成多态匹配
import java.util.ArrayList;
import java.util.List;
interface Iflyable{
void fly();
}
abstract class Transport{
String name;
public Transport(String name){
this.name=name;
}
void addOil(){
System.out.println("我是给交通工具加油的方法");
}
public abstract String toString();
}
class Airport extends Transport implements Iflyable{
public Airport(String name) {
super(name);
}
public void fly(){
System.out.println("我是飞机的飞行方法");
}
// 已经继承addOil()方法
public String toString(){
return "airport"+name;
}
}
abstract class Animal{
String name;
int height;
Animal(){
}
Animal(String name,int height){
this.name=name;
this.height=height;
}
abstract void eat();
public abstract String toString();
}
class Cat extends Animal{
int weight;// 比父类多一个属性weight
Cat(){
}
Cat(String name, int height, int weight) {
super(name, height);
this.weight=weight;
}
public void eat(){
System.out.println("我是cat的eat方法");
}
public String toString(){
return "我是动物"+name+":"+height+":"+weight;
}
}
class Bird extends Animal implements Iflyable{
Bird(){
}
Bird(String name) {// 比父类少一个属性
this.name=name;
}
public void eat(){
System.out.println("我是bird的eat方法");
}
public void fly(){
System.out.println("我是bird的飞翔方法");
}
public String toString(){
return "bird"+name;
}
}
public class testInterface {
public static void main(String[] args) {
Iflyable bird1 = new Bird();// 接口体现的多态
bird1.fly();
Animal bird2 = new Bird();// 继承体现的多态
bird2.eat();
// 将Animal的所有子类放入链表
List<Animal> objectList = new ArrayList<Animal>(10);
objectList.add(new Cat("cat1",12,13));
objectList.add(new Bird("bird1"));
System.out.println("用多态遍历链表<Animal>的结果为");
takeAnimals(objectList);
// 将Animal的所有子类放入数组
Animal[] objectArr = new Animal[5];
objectArr[0]=new Cat("cat2",14,15);
objectArr[1]=new Bird("bird2");
System.out.println("用多态遍历数组<Animal>的结果为");
takeAnimalsArr(objectArr);
// 将所有实现了飞翔接口的类放入链表
List<Iflyable> objectList2 = new ArrayList<Iflyable>(10);
objectList2.add(new Airport("boyin747"));
objectList2.add(new Bird("bird3"));
System.out.println("用多态遍历链表<Iflyable>的结果为");
takeIflable(objectList2);
Iflyable[] objectArr2 = new Iflyable[4];
objectArr2[0] = new Airport("boyin748");
objectArr2[1] = new Bird("bird4");
System.out.println("用多态遍历数组<Iflyable>的结果为");
takeIflableArr(objectArr2);
}
// 考虑用迭代器模式将对容器的遍历做成统一的
// 用多态遍历链表<Animal>
public static void takeAnimals(List<Animal> objectList){
for(Animal a:objectList){
System.out.println(a);
}
}
// 用多态遍历链表<Iflyable>
public static void takeIflable(List<Iflyable> objectList){
for(Iflyable a:objectList){
System.out.println(a);// 打印对象名就是调用toString()
}
}
// 用多态遍历数组<Animal>
public static void takeAnimalsArr(Animal[] objectList){
for(Animal a:objectList){
System.out.println(a);
}
}
// 用多态遍历数组<Iflyable>
public static void takeIflableArr(Iflyable[] objectList){
for(Iflyable a:objectList){
System.out.println(a);
}
}
}