设计一个抽象类Shape和它的实现类Oval,要求如下: (1)抽象类Shape表示形状对象,包含以下成员 ①属性:PI:double型常数,值为3.1415926; ②方法:double area(), 抽象方法;double perimeter(),抽象方法; (2)编写Shape类的子类Oval,表示椭圆对象,包含以下成员 ①属性:a:私有,double型,长轴半径;b:私有,double型,短轴半径; ②方法:Oval(double a,double b),构造方法,用参数设置椭圆的长轴半径和短轴半径 Oval(),构造方法,将椭圆的长轴半径和短轴半径都初始化为0。 double area(),重写Shape类中的area方法,返回椭圆的面积。 double perimeter(),重写Shape类中的perimeter方法,返回椭圆的周长。 public String toString( ),将把当前椭圆对象转换成字符串形式,例如长轴半径为8.0,短轴半径为6.0,返回字符串"Oval(a:8.0,b:6.0)"。 (3)编写测试类Main,创建一个长轴半径为8.0,短轴半径为6.0的椭圆对象,调用toString、area和perimeter方法,求出椭圆的面积和周长并输出,输出格式如下: The area of Oval(a:8.0,b:6.0) is 150.79644480000002 The perimeterof Oval(a:8.0,b:6.0) is 44.42882862370954
时间: 2024-02-15 14:01:47 浏览: 200
好的,以下是实现代码:
```java
// Shape.java
public abstract class Shape {
public final double PI = 3.1415926;
public abstract double area();
public abstract double perimeter();
}
// Oval.java
public class Oval extends Shape {
private double a;
private double b;
public Oval(double a, double b) {
this.a = a;
this.b = b;
}
public Oval() {
this(0, 0);
}
@Override
public double area() {
return PI * a * b;
}
@Override
public double perimeter() {
return 2 * PI * Math.sqrt((a * a + b * b) / 2);
}
@Override
public String toString() {
return "Oval(a:" + a + ",b:" + b + ")";
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Oval oval = new Oval(8.0, 6.0);
System.out.println("The area of " + oval.toString() + " is " + oval.area());
System.out.println("The perimeter of " + oval.toString() + " is " + oval.perimeter());
}
}
```
输出结果如下:
```
The area of Oval(a:8.0,b:6.0) is 150.79644480000002
The perimeter of Oval(a:8.0,b:6.0) is 44.42882862370954
```
阅读全文