1. 程式人生 > >抽象類,實現求矩形、圓形、三角形的面積計算。

抽象類,實現求矩形、圓形、三角形的面積計算。

package Abstrace;

import Abstrace.Circle;
import Abstrace.Rectangle;
import Abstrace.Shape;
import Abstrace.Triangle;


//定義一個抽象類
abstract class Shape{
public abstract void area();//定義一個抽象方法
}
class Rectangle extends Shape{//矩形類
private double height;
private double width;
//定義一個建構函式
public Rectangle(double height,double width){
this.height = height;
this.width = width;
}
//重寫抽象方法
public void area() {
// TODO Auto-generated method stub
double ss =(height*width);
System.out.println("所求矩形面積為"+ss);
}
}
class Circle extends Shape{//定義一個圓形類
private  double r;
public static final double PI = 3.14;
//定義一個建構函式
public Circle(double r){
this.r = r;
}
//重寫抽象方法
public void area() {
// TODO Auto-generated method stub
double ss =PI *r*r;
System.out.println("所求矩形面積為"+ss);
}
}
class  Triangle extends Shape{//定義一個三角形類
public double a;
public double b;
public double c;
//新增一個構造方法
public  Triangle(double a,double b,double c){
this.a = a;
this.b = b;
this.c = c;
}
//重寫抽象方法
public void area() {
// TODO Auto-generated method stub
double s1=(a+b+c)/2;
double s2 = s1*(s1-a)*(s1-b)*(s1-c); 
double result = Math.sqrt(s2); 
System.out.println("所求矩形面積為"+result);
}
}


public class ShapeDemo {
public static void main (String [] args){
Shape rectangle = new Rectangle(8.0,7.0);
Shape circle = new Circle(1.0);
Shape triangle = new Triangle(3.0,4.0,5.0);
rectangle.area();
circle.area();
triangle.area();
}
}