abstract class Animal{
public int age;
public abstract void info(); //抽象方法,子類必須實現該方法,如果父類有多個抽象方法,子類必須全部實現
}
class Bird extends Animal {
public String color;
public Bird(String color, int age) { //用構造方法初始化相關屬性,注意:構造方法不能被繼承!
this.color = color;
this.age = age;
}
public void info() { //實現父類的抽象方法,即重寫(覆蓋)父類的抽象方法
System.out.println("我是一隻"+color+"的鳥!\n今年"+age+"歲!"); //這裏最好使用this.age以免造成歧義。
}
}
class Fish extends Animal {
public int weight;
public Fish(int weight, int age) {
this.weight = weight;
this.age = age;
}
public void info() { //實現父類的抽象方法,即覆蓋 Animal 中的抽象方法 info()
System.out.println("我是一隻"+weight+"斤重的魚!\n今年"+this.age+"歲!");
}
}
public class Dm{
public static void main(String[] args){
Bird b = new Bird("藍色", 2);
b.info();
Fish f = new Fish(3, 1);
f.info();
}
}
/*--------------------------------
我是一隻藍色的鳥!
今年2歲!
我是一隻3斤重的魚!
今年1歲!
--------------------------------*/
- 抽象類和抽象方法都通過abstract關鍵字來修飾。
- 抽象類不能實例化。 抽象類中可以沒有、可以有一個或多個抽象方法,甚至可以全部爲抽象方法。
- 抽象方法只有方法聲明,沒有方法實現。有抽象方法的類聲明爲抽象類。子類必須重寫所有的抽象方法才能實例化,否則子類還是一個抽象類。