Java抽象類別和抽象方法例子

來源:互聯網
上載者:User

標籤:列印   方法   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抽象類別和抽象方法例子

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.