TestAbstract.java
class="java">//抽象类abstract //当一个类中含有抽象方法是,类是"残缺的",用abstract修饰为抽象的类, abstract class Animal { private String name; Animal(String name) { this.name = name; } //抽象方法,只有方法的定义,没有方法的具体实现,抽象方法就是用来重写的 public abstract void enjoy(); } //抽象类不能被实例化 abstract class Cat extends Animal { private String eyesColor; Cat(String n,String c) { super(n); eyesColor = c; } //在子类中可以不实现父类的抽象方法,仍为抽象方法,子类也要变为抽象类 public abstract void enjoy(); } class Dog extends Animal { private String furColor; Dog(String n,String c) { super(n); furColor = c; } public void enjoy() { System.out.println("狗叫声......"); } } class Bird extends Animal { Bird() { super("bird"); } public void enjoy() { System.out.println("鸟叫声......"); } } class Lady { private String name;//姓名 private Animal pet;//宠物Animal类 Lady(String name,Animal pet) { this.name = name; this.pet = pet; } //我的宠物高兴了 public void myPetEnjoy(){ pet.enjoy(); } } public class TestAbstract { public static void main(String args[]){ //抽象类Cat不能被实例化 //Cat c = new Cat("catname","blue"); Dog d = new Dog("dogname","black"); Bird b = new Bird(); //Lady l1 = new Lady("l1",c); Lady l2 = new Lady("l2",d); Lady l3 = new Lady("l3",b); //根据实际的对象来确定调用的方法,不是通过引用类型来确定的,不然就就一定调用Animal中的enjoy()方法, //l1.myPetEnjoy(); l2.myPetEnjoy(); l3.myPetEnjoy(); } }
?
?