我目前正在学习java。我的一个任务要求我们编写一些继承代码,它将在Eclipse的控制台中显示一个矩形。我试图运行它时不断收到标题中的错误,但无法弄清楚我做错了什么。任何提示或指导将不胜感激。
TestShape.java
public class TestShape {
public static void main(String[] args) {
double width = 5, length = 7;
Shape rectangle = new Rectangle(width, length);
System.out.println("Rectangle width: " + width + " and length: " + length
+ "\nResulting area: " + rectangle.area()
+ "\nResulting perimeter: " + rectangle.perimeter() + "\n");
}
}
Shape.java
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
public double getArea() {
// TODO Auto-generated method stub
return 0;
}
public double getPerimeter() {
// TODO Auto-generated method stub
return 0;
}
}
Rectangle.java
public abstract class Rectangle extends Shape {
private final double width, height, area, perimeter;
public Rectangle(double width, double height) {
this.width = width;
this.height= height;
this.area = width * height;
this.perimeter = 2 * (width + height);
}
@Override
public double getArea() {
return this.area;
}
@Override
public double getPerimeter() {
return this.perimeter;
}
}
答案 0 :(得分:2)
问题是你无法实例化abstract class
:
Shape rectangle = new Rectangle(width, length);
您无法删除abstract
类中的Rectangle
关键字,因为Shape
类中没有实现两种方法。
public abstract double area();
public abstract double perimeter();
要实例化,您需要创建concreate类,或者可以实现Rectangle
类中的所有方法,这些方法是从Shape
类继承的。
由于area()
和perimeter()
是Rectangle
类的功能,您可以实现这两种方法并从abstract
类中删除Rectangle
(现在这个类是具体课)。然后,您可以在main中实例化Rectangle
类。
答案 1 :(得分:1)
正如您在Shape类中定义了2个抽象方法,这些方法需要由Rectangle类实现,或者Rectangle类需要是抽象的。如果使Rectangle为abstract,则无法实例化。为了使代码能够进行最少的更改,请将 Rectangle 类实现改为:
public class Rectangle extends Shape {
private final double width, height, area, perimeter;
public Rectangle(final double width, final double height) {
this.width = width;
this.height = height;
this.area = width * height;
this.perimeter = 2 * (width + height);
}
@Override
public double getArea() {
return this.area;
}
@Override
public double getPerimeter() {
return this.perimeter;
}
@Override
public double area() {
return getArea();
}
@Override
public double perimeter() {
return getPerimeter();
}
}