1. 用abstract 修飾類時,則此類被稱之為抽象類

2. 含有抽象方法的類必須被聲明為抽象類,抽象類必須被繼承、抽象方法必須被重寫,否則子類就也要定義為抽象類及含有抽象方法,若子類繼承後沒有重寫方法,則出現錯誤 (Cat is not abstract and does not override abstract method enjoy() in Animal)

3. 抽象類不能被實例化,也就是不能以new產生新的物件,否則會出現錯誤 (Animal is abstract; cannot be instantiated)

4. 抽象方法只需被聲明,不需被實現

以下例子便可看出抽象類及方法的規則

abstract class Animal {
    public String name;
    Animal(String name){
        this.name = name;
    }
    /*
    public void enjoy() {
        System.out.println("叫聲...");
    }
    */    
    
    public abstract void enjoy();    
}

class Cat extends Animal {
    public String eyesColor;
    Cat(String n, String c) {
        super(n);
        this.eyesColor = c;
    }
    
    public void enjoy() {
        System.out.println("貓叫聲...");
    }    
}

class Dog extends Animal {
    public String furColor;
    Dog (String n, String f){
        super(n);
        this.furColor = f;
    }
    
    public void enjoy() {
        System.out.println("狗叫聲...");
    }    
}

class Bird extends Animal {
    public String furColor;
    Bird (String n, String f) {
        super(n);
        this.furColor = f;
    }
    
    public void enjoy() {
        System.out.println("鳥叫聲...");
    }    
}

class Lady {
    protected String name;
    private Animal pet;
    
    Lady (String name, Animal pet) {
        this.name = name;
        this.pet = pet;
    }
    
    public void myPetEnjoy() {
        pet.enjoy();
    }
}

public class Test {
    
    public static void main(String[] args) {
        
        Cat c = new Cat("Cat", "bule");
        Dog d = new Dog("Dog", "black");
        Bird b = new Bird("Bird", "green");
        Lady l1 = new Lady("Cindy", c);
        Lady l2 = new Lady("阿美", d);
        Lady l3 = new Lady("小花", b);
        
        System.out.print(l1.name + "的寵物發出");
        l1.myPetEnjoy();
        System.out.print(l2.name + "的寵物發出");
        l2.myPetEnjoy();
        System.out.print(l3.name + "的寵物發出");
        l3.myPetEnjoy();
        
    }
    
}

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 ced425 的頭像
    ced425

    Cedric's 學習備忘錄

    ced425 發表在 痞客邦 留言(1) 人氣()