1.求解用java写(如三角形,矩型,圆)的的周长,面积,要求用到继承,多态,抽象类,接口,内部类等。

惊鸿一捺 1年前 已收到1个回答 举报

恋你化身的猫 花朵

共回答了27个问题采纳率:92.6% 举报

//抽象的形状类
public abstract class Shape{ }
//接口
public interface IDisplay{
void display(); //显示图形的基本信息
double getArea(); //计算面积
double getGirth(); //计算周长
}
//三角形类
public class Triangle extends Shape implements IDisplay{
protected double a;
protected double b;
protected double c;
public Triangle(double a, double b, double c){
this.a = a; this.b = b; this.c = c;
}
@Override public double getArea() {
double s = (a + b + c) / 2;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
@Override public double getGirth() {
return this.a + this.b + this.c;
}
@Override public void display() {
System.out.println("三角形");
System.out.println("边长:" + a + ", " + b + ", " + c);
}
}
//矩形类
public class Rectangle extends Shape implements IDisplay {
protected double width; protected double height;
public Rectangle(double width, double height){
this.width = width;
this.height = height;
}
@Override public double getArea() {
return this.width * this.height;
}
@Override public double getGirth() {
return 2 * ( this.width + this.height);
}
@Override public void display() {
System.out.println("矩形");
System.out.println("宽:" + this.width + ", 高:" + this.height);
}
}
//圆类
public class Circle extends Shape implements IDisplay {
protected double radius;
public Circle(double radius){
this.radius = radius;
}
@Override public double getArea() {
return Math.PI * this.radius * this.radius;
}
@Override public double getGirth() {
return 2 * Math.PI * this.radius;
}
@Override public void display() {
System.out.println("圆");
System.out.println("半径:" + this.radius);
}
}

1年前

3
可能相似的问题
Copyright © 2024 YULUCN.COM - 雨露学习互助 - 17 q. 0.456 s. - webmaster@yulucn.com