求一道Java编程题!!!
求一道Java编程题!!!编写一个Java程序,在程序中定义一个抽象类Shape,有方法getArea计算面积和getLength计算周长。再定义二个Shape类的子类矩...
求一道Java编程题!!!编写一个Java程序,在程序中定义一个抽象类Shape,有方法getArea计算面积和getLength计算周长。再定义二个Shape类的子类矩形Rectangle、圆Circle类,完成这两种图形的面积和周长的计算,并进行测试
展开
1个回答
展开全部
public abstract class Shape {
public abstract double getArea();
public abstract double getLength();
}
public class Rectangle extends Shape{
private double length;
private double width;
public Rectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return width*length;
}
@Override
public double getLength() {
return width*2+length*2;
}
}
public class Circle extends Shape{
private double sidelength;
public Circle(double sidelength) {
super();
this.sidelength = sidelength;
}
@Override
public double getArea() {
return Math.pow(sidelength, 2);
}
@Override
public double getLength() {
return sidelength*4;
}
}
ublic class Test {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 6);
double area1=rectangle.getArea();
double length2=rectangle.getLength();
System.out.println("矩形的面积是:"+area1);
System.out.println("矩形的周长是:"+length2);
Circle circle = new Circle(7);
double area = circle.getArea();
double length = circle.getLength();
System.out.println("正方形的面积是:"+area);
System.out.println("正方形的周长是"+length);
}
}
//结果:
矩形的面积是:30.0
矩形的周长是:22.0
正方形的面积是:49.0
正方形的周长是28.0
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询