抽象類別,同時也是父類別:
public abstract class Shape {
// 抽象類別不能拿來產生新的物件,也常被抽離出來當父類別。
// 抽象類別可以有屬性,也可以沒有。
// 抽象類別可以更節省程式碼。
public abstract double calArea();
// 抽象方法不能有具體作為,在此例子之下,它只是被子類別實作具體行為。
}
子類別之圖形:
public class Circle extends Shape {
int radius;
double pi=3.1415926;
public double calArea() {
return pi*radius*radius;
} // 它覆寫了父類別的抽象方法,有實作具體行為。
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
子類別之矩形:
public class Rectangle extends Shape {
int length;
int width;
public double calArea(){
return length*width;
} // 它覆寫了父類別的抽象方法,有實作具體行為。
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
主程式:
public class Main {
public static void main(String[] args) {
Shape c1 = new Circle(); // 模糊寫法,口語的說法是 形狀 c1 是圓形。
Shape r1 = new Rectangle(); // 模糊寫法,口語的說法是 形狀 r1 是方形。
((Circle)c1).setRadius(10); // 這邊要強制轉型,不然電腦認為 c1 仍是 Shape 。
((Rectangle)r1).setLength(10);
((Rectangle)r1).setWidth(5);
System.out.println(c1.calArea()); // 這邊不用強制轉型, Shape 裡面本來就有 calArea。
System.out.println(r1.calArea());
}
}
這邊再次複習前一篇的練習,子類覆寫了父類別中的方法,所以該 shape 物件使用父類別的方法時,效果是覆寫後的。
結果:
314.15926
50.0
Process finished with exit code 0
沒有留言:
張貼留言