编写Point、Circle、Cylinder三个类之间具有层次结构的类。 Point类中有x,y属性,定义构造函数,及计算面积的方法double area()和toString()方法; Circle类中增加一个半径double radius属性,定义构造函数,及计算面积的方法double area()(重写父类的方法)、计算周长的方法double perimeter()和toString()方法; Cylinder类增加一个高height属性,定义构造函数,及计算表面积的方法double area()(重写父类的方法)和计算体积的方法double volume()和toString方法。 要求:所有的属性都是私有的。 提示:圆继承的点作为圆心,圆柱体继承圆作为底面和顶面。 最终定义测试类。java
时间: 2023-06-01 17:04:13 浏览: 198
关于多态性和虚函数应用的典型实例
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;
}
public String toString() {
return "(" + 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;
}
public String toString() {
return "Circle: center" + super.toString() + ", radius=" + 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 super.perimeter() * height + 2 * super.area();
}
public double volume() {
return super.area() * height;
}
public String toString() {
return "Cylinder: center" + super.toString() + ", height=" + height;
}
}
public class Test {
public static void main(String[] args) {
Point p = new Point(1, 2);
Circle c = new Circle(1, 2, 3);
Cylinder cy = new Cylinder(1, 2, 3, 4);
System.out.println(p.toString());
System.out.println(c.toString());
System.out.println(cy.toString());
}
}
阅读全文