用Java编写一个Geometry 的子类Triangle,可以计算三角形的面积,在主类中让Student
发布网友
发布时间:2022-05-20 20:19
我来回答
共1个回答
热心网友
时间:2023-11-22 13:10
public class TestMain {
public static void main(String[] args) {
Student zhang = new Student("zhang");
zhang.g = new Trianglle(3,4,5);
double x = zhang.area();
zhang.g = new Circlle(3);
double y = zhang.area();
zhang.g = new Circlle(5);
double z = zhang.area();
System.out.println("面积之和是:"+(x+y+z));
}
}
class Geometry {
public double area() {
return 0;
}
final double pi = 3.1415926;
}
class Trianglle extends Geometry{
private double side1;
private double side2;
private double side3;
public Trianglle(double s1,double s2,double s3){
side1 = s1;
side2 = s2;
side3 = s3;
}
public double perimeter(){
return side1 + side2 + side3;
}
public double area(){
double s = perimeter()/2;
return Math.sqrt(s*(s - side1)*(s - side2)*(s - side3));
}
}
class Circlle extends Geometry{
private double radius;
public Circlle(double r){
radius = r;
}
public double area(){
return pi*radius*radius;
}
}
class Student {
String name;
Geometry g;
public Student(String name){
this.name = name;
}
public double area(){
return g.area();
}
}