標籤:列印 方法 void sha private ati 圓形 抽象 iam
題目:定義Shape類表示一般二維圖形。Shape具有抽象方法area和perimeter,分別計算形狀的面積和周長。試定義一些2D 圖形類(如矩形、三角形、圓形等),這些均為Shape類的子類並計算出這些形狀的面積和周長,列印輸出相關資訊。
代碼:
//形狀類
public abstract class Shape { public abstract double area(); public abstract double perimeter();}
//矩形類
public class Rectangle extends Shape { private double length; private double width; public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } @Override public double area() { return getLength() * getWidth(); } @Override public double perimeter() { return 2 * (getWidth() + getWidth()); }}
//三角形類
public class Triangle extends Shape { private double a, b, c; public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } @Override public double area() { double p = (getA() + getB() + getC()) / 2; return Math.sqrt(p * (p - getA()) * (p - getB()) * (p - getC())); } @Override public double perimeter() { return getA() + getB() + getC(); }}
//圓形類
public class Circle extends Shape { private double diameter; public double getDiameter() { return diameter; } public void setDiameter(double diameter) { this.diameter = diameter; } @Override public double area() { return Math.PI * Math.pow(getDiameter() / 2, 2); } @Override public double perimeter() { return Math.PI * getDiameter(); }}
//測試代碼
public class 測試 { public static void main(String [] args){ Rectangle rec = new Rectangle(); rec.setLength(10); rec.setWidth(5); double rec_area = rec.area(); double rec_perimeter = rec.perimeter(); System.out.println("矩形的面積:"+rec_area+",周長"+rec_perimeter); Triangle tri = new Triangle(); tri.setA(3); tri.setB(4); tri.setC(5); double tri_area = tri.area(); double tri_perimeter = tri.perimeter(); System.out.println("三角形的面積:"+tri_area+",周長"+tri_perimeter); Circle cir = new Circle(); cir.setDiameter(10); double cir_area = cir.area(); double cir_perimeter = cir.perimeter(); System.out.println("圓形的面積:"+cir_area+",周長"+cir_perimeter); }}
Java抽象類別和抽象方法例子