1. 程式人生 > >通過程式設計幾何圖形(Shape)、矩形(Rectangle)、圓形(Circle)、正方形(Square)幾種型別, 能夠利用介面和多型性計算幾何圖形的面積和周長並顯示。

通過程式設計幾何圖形(Shape)、矩形(Rectangle)、圓形(Circle)、正方形(Square)幾種型別, 能夠利用介面和多型性計算幾何圖形的面積和周長並顯示。

interface Shape {//宣告介面Shape
final float PI = 3.14f; // 定義常量圓周率
abstract void area();//定義抽象方法面積
abstract void perimeter();//定義抽象方法周長
}


class bian {
double width;// 定義變數寬
double length;// 定義變數長
double radius; // 定義變數半徑
double S;// 定義變數面積
double C;// 定義變數周長


public bian(double width, double length, double radius) {
this.width = width;

this.length = length;
this.radius = radius;
}
}


class Rectangle extends bian implements Shape {//實現介面
public Rectangle(double width, double length, double radius) {
super(width, length, radius);
}


public void area() {
S = width * length;
System.out.println("矩形面積:" + S);// 輸出
}


public void perimeter() {
C = (width + length) * 2;

System.out.println("矩形周長:" + C);// 輸出
}
}


class Circle extends bian implements Shape {//實現介面
public Circle(double width, double length, double radius) {
super(width, length, radius);
}


public void area() {
S = PI * radius * radius;
System.out.println("圓形面積:" + S);// 輸出
}


public void perimeter() {
C = 2 * PI * radius;

System.out.println("圓形周長:" + C);// 輸出


}


}


class Square extends bian implements Shape {//實現介面
public Square(double width, double length, double radius) {
super(width, length, radius);
}


public void area() {
S = width * width;
System.out.println("正方形面積:" + S);// 輸出
}


public void perimeter() {
C = (width + width) * 2;
System.out.println("正方形周長:" + C);// 輸出


}


}
public class jiekoutuxing {


public static void main(String[] args) {
Shape p1;//宣告介面變數
p1 = new Rectangle(4.0, 5.0, 0);//實現類物件賦值介面變數
p1.area();//介面回撥
p1.perimeter();//介面回撥


p1 = new Circle(0, 0, 2.0);//實現類物件賦值介面變數
p1.area();
p1.perimeter();


p1 = new Square(3.0, 0, 0);//實現類物件賦值介面變數
p1.area();
p1.perimeter();
}


}