编写Shape抽象类,包含计算图形的表面积和体积的两个方法。定义Circle类求圆柱体的表面积和体积,Rectangle类求矩形体的表面积和体积,在测试类Test里创建对象并输出结果。
Shape类:
public abstract class Shape {
abstract double Area();
abstract double Volume();
}
Circle类
public class Circle extends Shape{
public double Pi = 3.14;
int r,h;
void Circle(){
this.r = r;
this.h = h;
this.Pi = Pi;
}
public double Area(){
return 2 * Pi * r * h;
}
public double Volume(){
return Pi * r * r * h;
}
}
Rectangle类
public class Rectangle extends Shape {
int l, w, h;
void Rectangle() {
this.l = l;
this.w = w;
this.h = h;
}
public double Area() {
//表面积
return (l * w + l * h + h * w) * 2;
}
public double Volume() {
//体积
return l * w * h;
}
}
Test类
public class Test {
public static void main(String[] ages) {
Rectangle s = new Rectangle();
Circle c = new Circle();
s.h = 3;
s.l = 4;
s.w = 2;
System.out.println("长方体的表面积为:" + s.Area());
System.out.println("长方体的体积为:" + s.Volume());
c.Pi = 3.14;
c.r = 2;
c.h = 3;
System.out.println("圆锥体的表面积为:" + s.Area());
System.out.println("圆锥体的体积为:" + s.Volume());
}
}
涉及技术:抽象类的定义和使用