1、用abstract关键字来修饰一个类时,这个类叫做抽象类;用abstract来修饰一个方法时,该方法叫做抽象方法。
2、含有抽象方法的类必须被声明抽象类,抽象类必须被继承,抽象方法必须被重写。
3、抽象类不能被实例化。
4、抽象方法只需声明,而不需实现。
public class TestPolymorphic{ public static void main(String args[]){ //Animal animal = new Animal("animal"); 抽象类不能被实例化 Cat cat = new Cat("cat","blue"); Dog dog = new Dog("dog","black"); //Lily l1 = new Lily("l1",animal); Lily l2 = new Lily("l2",dog); //l1.myAnimalEnjoy(); l2.myAnimalEnjoy(); } } class Lily{ private String name; private Animal animal; public Lily(String name, Animal animal){ this.name = name; this.animal = animal; } public void myAnimalEnjoy(){ animal.enjoy(); } } abstract class Animal{ //声明抽象类 private String name; public Animal(String name){ this.name = name; } /*public void enjoy(){ System.out.println("叫声~~~"); }*/ public abstract void enjoy(); //声明抽象方法 } class Dog extends Animal{ private String forlorColor; public Dog(String name,String forlorColor){ super(name); this.forlorColor = forlorColor; } public void enjoy(){ System.out.println("dog叫声~~~"); } } class Cat extends Animal{ private String eyesColor; public Cat(String name,String eyesColor){ super(name); this.eyesColor = eyesColor; } public void enjoy(){ System.out.println("cat叫声~~~"); } }
运行结果:
总结:抽象类一般是用在多态。