抽象类Animal:
public abstract class Animal { ?? ?public abstract void eat();
}
子类Cat: public class Cat extends Animal {
?? ?@Override
?? ?public void eat() {
?? ??? ?System.out.println("猫在吃鱼");
?? ?}
}
子类Dog:
public class Dog extends Animal { ?? ?@Override ?? ?public void eat() { ?? ??? ?System.out.println("狗吃骨头"); ?? ?}
}
测试Test类:
/* ?* 将抽象类类型,作为方法的参数进行传递 ?*/ public class Test { ?? ?public static void main(String[] args) { ?? ?//调用operatorAnimal,传递子类对象 ?? ??? ?Cat c=new Cat(); ?? ??? ?operatorAnimal(c); ?? ??? ?operatorAnimal(new Dog()); ?? ?} ?? ?/* ?? ? * 方法operatorAnimal,参数是一个抽象类 ?? ? * 调用方法,传递Animal类型对象,Animal抽象类没有对象 ?? ? * 只能传递Animal的子类的对象(多态) ?? ? */ ?? ?public static void operatorAnimal(Animal a){ ?? ??? ?//引用变量a,调用方法eat ?? ??? ?a.eat(); ?? ?} }
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|