编写Point、Circle、 Cylinder三个类之间具有层次结构的类。 Point类中有xy属性,定义构造函数,及计算面积的方法double area0和toString0方 法; Circle类中增加一个半径double radius属性,定义构造函数,及计算面积的方法double area0(重写父类的方法)、计算周长的方法double perimeterQ和toString0方法; Cylinder类增加一个高height属性,定义构 造函数,及计算表面积的方法double area0( 重写父类的方法)和计算体积的方法double volume0和toString方法。 要求:所有的属性都是私有的。 提示:圆继承的点作为圆心,圆柱体继承 圆作为底面和顶面。 最终定义测试类。
时间: 2023-05-30 11:02:45 浏览: 119
class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double area() {
return 0;
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
class Circle extends Point {
private double radius;
public Circle(double x, double y, double radius) {
super(x, y);
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
public double perimeter() {
return 2 * Math.PI * radius;
}
@Override
public String toString() {
return "Circle(" + super.toString() + ", " + radius + ")";
}
}
class Cylinder extends Circle {
private double height;
public Cylinder(double x, double y, double radius, double height) {
super(x, y, radius);
this.height = height;
}
@Override
public double area() {
return 2 * super.area() + 2 * Math.PI * radius * height;
}
public double volume() {
return super.area() * height;
}
@Override
public String toString() {
return "Cylinder(" + super.toString() + ", " + height + ")";
}
}
public class Test {
public static void main(String[] args) {
Point p = new Point(0, 0);
System.out.println(p + " Area: " + p.area());
Circle c = new Circle(0, 0, 5);
System.out.println(c + " Area: " + c.area() + " Perimeter: " + c.perimeter());
Cylinder cy = new Cylinder(0, 0, 5, 10);
System.out.println(cy + " Area: " + cy.area() + " Volume: " + cy.volume());
}
}
阅读全文