GeometricObject和circle类

时间:2015-03-25 00:28:29

标签: java

为什么我不能从GeometricObject类调用这些方法?

public abstract class GeometricObject {
    private String color = "white";
    private boolean filled;
    private java.util.Date dateCreated;

    /** Construct a default geometric object */
    protected GeometricObject() {
        dateCreated = new java.util.Date();
    }

    /** Construct a geometric object with color and filled value */
    protected GeometricObject(String color, boolean filled) {
        dateCreated = new java.util.Date();
        this.color = color;
        this.filled = filled;
    }

    /** Return color */
    public String getColor() {
        return color;
    }

    /** Set a new color */
    public void setColor(String color) {
        this.color = color;
    }

    /** Return filled. Since filled is boolean,
    *  the get method is named isFilled */
    public boolean isFilled() {
        return filled;
    }

    /** Set a new filled */
    public void setFilled(boolean filled) {
        this.filled = filled;
    }

    /** Get dateCreated */
    public java.util.Date getDateCreated() {
        return dateCreated;
    }

    @Override
    public String toString() {
        return "created on " + dateCreated + "\ncolor: " + color +
            " and filled: " + filled;
    }

    /** Abstract method getArea */
    public abstract double getArea();

    /** Abstract method getPerimeter */
    public abstract double getPerimeter();
}

1 个答案:

答案 0 :(得分:0)

如果你的意思是为什么你不能调用getArea()getPerimeter()方法,那是因为它们是抽象的。

您无法调用抽象方法。抽象方法必须在具体类中具有实现。

此外,您无法实例化接口或抽象类。您只能实例化具体的类(并且它们可以实现接口或扩展抽象类)。

因此,要使用getArea()getPerimeter()方法,您需要一个实现它们的具体类。比如类可能看起来像这样:

public class ConcreteGeometricObject extends GeometricObject {

    public ConcreteGeometricObject() {
        super();
    }

    public ConcreteGeometricObject(String color, boolean filled) {
        super(color, filled);
    }

    @Override
    public double getArea() {
        double area;
        //implementation code here
        return area;
    }

    @Override
    public double getPerimeter() {
        double perimeter;
        //implementation code here
        return perimeter;
    }
}

你可以用这样的方式使用它:

GeometricObject geometricObject = new ConcreteGeometricObject();
//...
double area = geometricObject.getArea();
double perimeter = geometricObject.getPerimeter()

请阅读此追踪:Lesson: Interfaces and Inheritance