public class Test { public static void main(String[] args) { Rectangle rectangle = new Rectangle(3.00, 4.00); System.out.println("矩形的长为"+rectangle.length+','+"宽为"+rectangle.wide); System.out.printf("矩形的周长为:%5.2f,面积为:%5.2f",rectangle.perimeter(),rectangle.area()); System.out.println(""); Cone cone = new Cone(rectangle, 3.00,"矩形"); System.out.printf("底面积%5.2f,高为%.2f的%s锥,体积为:%-5.2f",rectangle.area(),cone.height,cone.coneName,cone.V()); Triangle triangle = new Triangle(3.0, 4.0, 5.0); System.out.println("三角形的三边长为:"+triangle.a+'、'+triangle.b+'、'+triangle.c); System.out.printf("三角形的周长为:%5.2f,面积为:%5.2f",triangle.perimeter(),triangle.area()); System.out.println(""); Cone cone1 = new Cone(triangle, 3.00,"三角形"); System.out.printf("底面积%5.2f,高为%.2f的%s锥,体积为:%-5.2f",triangle.area(),cone1.height,cone1.coneName,cone1.V()); Cicle cicle = new Cicle(3.0); System.out.println("圆的半径为:"+cicle.r); System.out.printf("圆的周长为:%5.2f,面积为:%5.2f",cicle.perimeter(),cicle.area()); System.out.println(""); Cone cone2 = new Cone(cicle, 3.00,"圆"); System.out.printf("底面积:%5.2f, 高为%.2f的%s锥, 体积为:%-5.2f", cicle.area(), cone2.height, cone2.coneName, cone2.V()); } }如何修改使用上转型对象
时间: 2024-02-15 21:05:10 浏览: 82
可以使用父类的引用来引用子类对象,这样就可以实现上转型。具体修改如下:
```
public class Test {
public static void main(String[] args) {
Shape shape;
Rectangle rectangle = new Rectangle(3.00, 4.00);
System.out.println("矩形的长为"+rectangle.length+','+"宽为"+rectangle.wide);
System.out.printf("矩形的周长为:%5.2f,面积为:%5.2f",rectangle.perimeter(),rectangle.area());
System.out.println("");
shape = rectangle;
Cone cone = new Cone(shape, 3.00,"矩形");
System.out.printf("底面积%5.2f,高为%.2f的%s锥,体积为:%-5.2f",rectangle.area(),cone.height,cone.coneName,cone.V());
System.out.println("");
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
System.out.println("三角形的三边长为:"+triangle.a+'、'+triangle.b+'、'+triangle.c);
System.out.printf("三角形的周长为:%5.2f,面积为:%5.2f",triangle.perimeter(),triangle.area());
System.out.println("");
shape = triangle;
Cone cone1 = new Cone(shape, 3.00,"三角形");
System.out.printf("底面积%5.2f,高为%.2f的%s锥,体积为:%-5.2f",triangle.area(),cone1.height,cone1.coneName,cone1.V());
System.out.println("");
Cicle cicle = new Cicle(3.0);
System.out.println("圆的半径为:"+cicle.r);
System.out.printf("圆的周长为:%5.2f,面积为:%5.2f",cicle.perimeter(),cicle.area());
System.out.println("");
shape = cicle;
Cone cone2 = new Cone(shape, 3.00,"圆");
System.out.printf("底面积:%5.2f, 高为%.2f的%s锥, 体积为:%-5.2f", cicle.area(), cone2.height, cone2.coneName, cone2.V());
}
}
```
这样就可以通过 `Shape` 类型的引用来引用所有的子类对象,实现了上转型。
阅读全文