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叫聲~~~"); } }
執行結果:
總結:抽象類一般是用在多型。