抽象类
用abstract关键字来修饰一个类时,这个类叫做抽象类;用abstract来修饰一个方法时,这个方法叫抽象方法。
含有抽象方法的类必须被声明为抽象类,抽象类必须被继承,抽象方法必须被重写。
抽象类不能被实例化。
抽象方法只需声明,而不需要实现。
例如下
public class Test { public static void main(String args[]) { 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); l1.myPetEnjoy(); l2.myPetEnjoy(); l3.myPetEnjoy(); } } //定义抽象类 abstract class Animal { private String name; Animal(String name) { this.name = name; } /*public void enjoy() { System.out.println("动物叫声........"); }*/ public abstract void enjoy(); } class Cat extends Animal { private String eyesColor; Cat(String n,String c) {super(n); eyesColor = c;} public void enjoy() { System.out.println("喵喵喵............"); } } 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类型的pet Lady(String name,Animal pet) { this.name = name; this.pet = pet; } public void myPetEnjoy() {pet.enjoy();} }