編程:定義一個抽象類Shape,它包含兩個抽象方法area()和perimeter(),從Shape類派生出Circle類和Rectangle類,這兩個類都用area()方法來計算面積,用perimeter()方法來計算周長。撰寫應用程式使用Circle類和Rectangle類,還要進行測驗。
uj5u.com熱心網友回復:
shape抽象類public interface IShape {
double area();
double perimeter();
}
circle實作shape類
public class Circle implements IShape {
private double r;
public Circle (double r) {
this.r = r;
}
@Override
public double area() {
return Math.PI * r * r;
}
@Override
public double perimeter() {
return Math.PI * r * 2;
}
}
rectangle實作shape抽象類
public class Rectangle implements IShape {
private double width;
private double length;
public Rectangle (double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double area() {
return width * length;
}
@Override
public double perimeter() {
return 2 * (width + length);
}
}
測驗類,以及測驗結果
package shape;
public class Test {
public static void main (String[] args) {
IShape shape = new Circle(2.3);
System.out.println("圓形面積: " + shape.area());
System.out.println("圓形周長: " + shape.perimeter());
shape = new Rectangle(2, 3);
System.out.println("長方形面積: " + shape.area());
System.out.println("長方形周長: " + shape.perimeter());
}
}
測驗實體結果
圓形面積: 16.619025137490002
圓形周長: 14.451326206513047
長方形面積: 6.0
長方形周長: 10.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/118871.html
標籤:Java相關
上一篇:在spring security 下發送post請求回傳405錯誤
下一篇:JDK 8 的安裝與配置
