Shape類-2
阿新 • • 發佈:2018-12-17
Description
定義一個形狀類Shape,提供計算周長getPerimeter()和麵積getArea()的函式 定義一個子類正方形類Square繼承自Shape類,擁有邊長屬性,提供建構函式,能夠計算周長getPerimeter()和麵積getArea() 定義一個子類長方形類Rectangle繼承自Square類,擁有長、寬屬性,提供建構函式,能夠計算周長getPerimeter()和麵積getArea() 定義一個子類圓形類Circle繼承自Shape,擁有半徑屬性,提供建構函式,能夠計算周長getPerimeter()和麵積getArea() 在main函式中,分別構造三個Shape類的變數,分別指向一個Square、Rectangle、Circle物件,並輸出他們的周長、面積.
import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); double k = sc.nextDouble(); Square s = new Square(k); System.out.println(String.format("%.2f",s.getPerimeter())+" "+String.format("%.2f", s.getArea())); k = sc.nextDouble(); double l = sc.nextDouble(); Rectangle r = new Rectangle(k,l); System.out.println(String.format("%.2f",r.getPerimeter())+" "+String.format("%.2f", r.getArea())); k = sc.nextDouble(); Circle c = new Circle(k); System.out.println(String.format("%.2f",c.getPerimeter())+" "+String.format("%.2f", c.getArea())); sc.close(); } } class Shape{ //int Bc; //Shape(){} double getPerimeter() { return 0; } double getArea() { return 0; } } class Square extends Shape{ double l ;//長 Square(double l){ this.l = l; } double getPerimeter() { return l*4; } double getArea() { return l*l; } } class Rectangle extends Square{ double h;//寬 Rectangle(double l,double h) { super(l); this.h = h; // TODO Auto-generated constructor stub } double getPerimeter() { return 2.0*(l+h); } double getArea() { return l*h; } } class Circle extends Shape{ double r;//半徑 Circle(double r){ this.r = r; } double getPerimeter() { return 2.0*Math.PI*r; } double getArea() { return Math.PI*r*r; } }