代码错误import java.util.Scanner; public class Main{ public static void main (String args[]){ Scanner sc=new Scanner(System.in); double a=sc.nextDouble(); double b=sc.nextDouble(); Shape s=new Oval(a,b); System.out.println("The area of "+s.toString()+" is "+s.area()); System.out.println("The perimeterof "+s.toString()+" is "+s.perimeter()); }} class Shape{ abstract double area(); abstract double perimeter(); } class Oval extends Shape{ private double a; //长轴半径 private double b; //短轴半径 Oval(double a,double b){ this.a= a; this.b= b; } Oval(){ this.a=0; this.b=0; } double area(){ return Math.PI*a*b; } double perimeter(){ return 2*Math.PI*b+4*(a-b); //L=2πb+4(a-b) } public String toString() { return "Oval(a:" + this.a + ",b:" + this.b + ")"; } }
时间: 2024-01-07 18:04:19 浏览: 68
这段代码有一个错误,因为抽象类 Shape 中的方法没有被声明为抽象方法。在 Java 中,如果一个类有抽象方法,那么这个类必须被声明为抽象类。因此,你需要在 Shape 类中将 area() 和 perimeter() 方法声明为抽象方法,如下所示:
```
abstract class Shape {
abstract double area();
abstract double perimeter();
}
```
另外,你还需要将 Oval 类的构造函数声明为 public,否则在其他类中无法访问该构造函数。
修复后的代码如下:
```
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
Shape s = new Oval(a, b);
System.out.println("The area of " + s.toString() + " is " + s.area());
System.out.println("The perimeter of " + s.toString() + " is " + s.perimeter());
}
}
abstract class Shape {
abstract double area();
abstract double perimeter();
}
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.a = 0;
this.b = 0;
}
@Override
double area() {
return Math.PI * a * b;
}
@Override
double perimeter() {
return 2 * Math.PI * b + 4 * (a - b); //L=2πb+4(a-b)
}
public String toString() {
return "Oval(a:" + this.a + ",b:" + this.b + ")";
}
}
```
阅读全文