1、创建一个Shape形状类,包括一个getArea求面积方法,一个getC求周长方法 创建3个子类圆、矩形、三角形,分别求他们的面积和周长,并创建test类进行测试 您所在的位置:网站首页 编程求正方形面积 1、创建一个Shape形状类,包括一个getArea求面积方法,一个getC求周长方法 创建3个子类圆、矩形、三角形,分别求他们的面积和周长,并创建test类进行测试

1、创建一个Shape形状类,包括一个getArea求面积方法,一个getC求周长方法 创建3个子类圆、矩形、三角形,分别求他们的面积和周长,并创建test类进行测试

2024-06-24 07:09| 来源: 网络整理| 查看: 265

1、创建一个Shape形状类,包括一个getArea求面积方法,一个getC求周长方法 2、创建3个子类Circle圆、Rectangle矩形、Triangle三角形,分别有各自的构造方法,并重新父类的求面积、求周长方法 3、创建一个Test类,对以上的类创建对象进行测试

答案: 下面展示一些 代码。

//Shape类的创建 public class Shape { //求面积的方法 public double getArea() { return 0; } //求周长的方法 public double getC() { return 0; } } //子类圆的创建的创建 public class Circle extends Shape{ protected int r; //有形参的构造方法 public Circle(int r) { this.r=r; } public int getR() { return r; } //方法的重写 public double getArea() { return Math.PI*r*r; } public double getC() { return Math.PI*2*r; } //子类矩形类的继承 public class Rectangle extends Shape { private int weight; private int height; public Rectangle(int weight,int height) { this.weight=weight; this.height=height; } public int getweight() { return weight; } public int getheight() { return height; } //方法的重写 public double getArea() { return weight*height; } public double getC() { return 2*weight*height; } //子类三角行类的继承 public class Triangle extends Shape { private int a; private int b; private int c; double s; public Triangle(int a,int b,int c) { //是否能构成三角形 if(a+b>c&&a+c>b&&b+c>a) { this.a=a; this.b=b; this.c=c; }else { System.out.println("你输入的三边长无法构成三角形请重新输入"); } } public int geta() { return a; } public int getb() { return b; } public int getc() { return c; } //方法的重写 public double getArea() { s=(a+b+c)/2; return Math.sqrt((s-a)*(s-b)*(s-c)); } public double getC() { return a+b+c; } //进行测试 public class Test1 { public static void main(String[]args) { Circle circle1=new Circle(4); System.out.println("圆的面积是"+circle1.getArea()); System.out.println("圆的周长是"+circle1.getC()); Rectangle rectangle1=new Rectangle(3, 4); System.out.println("矩形的面积是"+rectangle1.getArea()); System.out.println("矩形的周长是"+rectangle1.getC()); Triangle triangle1=new Triangle(3, 4, 5); System.out.println("三角形的面积是"+triangle1.getArea()); System.out.println("三角形的周长是"+triangle1.getC()); }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有