作业帮 > 综合 > 作业

用Java语言编写,要求申明三角形类,继承图形抽象类,计算三角形的周长和面积!

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/05/12 18:03:06
用Java语言编写,要求申明三角形类,继承图形抽象类,计算三角形的周长和面积!
用Java语言编写,要求申明三角形类,继承图形抽象类,计算三角形的周长和面积!
图形抽象类的代码:
abstract class MyShape {
abstract int calGirth(); //求周长
abstract double calSquare(); //求面积
}
三角形类的实现:
public class Triangle extends MyShape{
int borderA,borderB,borderC;
Triangle(int a,int b,int c){borderA = a; borderB = b; borderC = c;}
Triangle(){borderA = borderB = borderC = 0;}
@Override
int calGirth() {
return borderA + borderB + borderC;
}
@Override
double calSquare() {
double p = calGirth() / 2;
return Math.sqrt(p * (p - borderA) * (p - borderB) * (p - borderC));
}
public static void main(String[] args) {
Triangle test = new Triangle(3,4,5);
System.out.println("The girth of the triangle is " + test.calGirth());
System.out.println("The square of the triangle is " + test.calSquare());
}
}
实现两个抽象函数,测试结果正确,输出为:
The girth of the triangle is 12
The square of the triangle is 6.0