abstract 概述
- 1.用abstract關鍵字修飾一個類時,叫抽象類。用abstract關鍵字修飾一個方法時,叫抽象方法
- 2.含有抽象方法的類必須被聲明爲抽象類,抽象類必須被繼承,抽象方法必須被重寫
- 3.抽象類不能被實例化
- 4.抽象方法只需聲明,不需實現
- 5.繼承抽象類的也能夠是抽象類,重寫的抽象方法仍是抽象方法
代碼一發
abstract class Animal {
private String name;
Animal(String name) {
this.name = name;
}
public abstract void enjoy();
//System.out.println("animalshout...");
}
class Cat extends Animal {
private String eyesColor;
Cat(String n,String c) {
super(n);
eyesColor = c;
}
public void enjoy() {
System.out.println("catshoult...");
}
}
class Dog extends Animal {
private String furColor;
Dog(String n,String c) {
super(n);
furColor = c;
}
public void enjoy() {
System.out.println("dogshoult...");
}
}
class Lady {
private String name;
private Animal pet;
Lady(String name, Animal pet) {
this.name = name;
this.pet = pet;
}
public void myPetEnjoy() {
pet.enjoy();
}
}
public class TestTai {
public static void main(String[] args) {
Cat c = new Cat("catname", "blue");
Dog d = new Dog("d ogname", "black");
Lady l1 = new Lady("l1", c);
Lady l2 = new Lady("l2", d);
l1.myPetEnjoy();
l2.myPetEnjoy();
}
}