抽象类,实现求矩形、圆形、三角形的面积计算。

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();
}
}
  • 7
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值