java - 覆盖 toString 时遇到问题

标签 java syntax overriding

我遇到的主要问题是覆盖toString()以及到底要放什么。如果有人可以提供帮助那就太好了!

// Circle inherits from GeometricObject and uses Drawable

public class Circle extends GeometricObject {
    private double radius;

    /**Default constructor*/
    public Circle() {
        this(1.0);
    }

    /**Overloaded constructor - construct a circle with a specified radius*/
    public Circle(double radius) {
        //call the local overloaded constructor and pass it the following: radius, "white", false
        this.radius = radius;
    }

    /**Overloaded constructor - construct a circle with specified radius, filled, and color*/
    public Circle(double radius, String color, boolean filled) {
        //call the GeometricObject's constructor and pass it color and filled
        this.radius = radius;
        setColor(color);
        setFilled(filled);
    }

    /**Return radius*/
    public double getRadius() {
        return radius;
    }

    /**Set a new radius*/
    public void setRadius(double radius) {
        this.radius = radius;
    }

    /**Implement the getArea method defined in GeometricObject*/
    public double getArea() {
        return radius*radius*Math.PI;
    }

    /**Implement the getPerimeter method defined in GeometricObject*/
    public double getPerimeter() {
        return 2*radius*Math.PI;
    }

    /**Override the equals() method defined in the Object class*/
    public boolean equals(Circle circle) {
        return this.radius == circle.getRadius();
    }

这是我的代码遇到的主要问题。我需要有关 toString() 方法如何工作以及要输入什么内容的帮助!

    /**Override the toString() method defined in the Object class*/
    //output for circle should be: "[Circle] radius = ; color = ;               filled = " : insert appropriate variables to the right of the equal sign
    @Override
    public String toString() {
        return [Circle]
    }

    @Override
    public String Draw() {

    }

    @Override
    public String howToDraw() {

    }
}

最佳答案

难点在哪里?

return "[Circle] radius: "+this.radius+" ; color = "+this.color+";";

如果颜色是私有(private)的(在父类(super class)中),你应该使用这样的东西:

return "[Circle] radius: "+this.radius+" ; color = "+getColor()+";";

关于java - 覆盖 toString 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094337/

相关文章:

powershell - Foreach 循环中的多个变量 [PowerShell]

javascript - JavaScript 中 var num=30 和 var num=new Number(30) 有什么区别?

java - 访问子类中的隐藏字段

android - 在 Android 中覆盖 ArrayAdapter

java - 使用 Maven 只重建必要的 jar

java - 在mobilefirst中调用java适配器时如何解决此错误 "java.security.cert.CertificateException:"?

arrays - Perl:对数组使用条件

html - ul 传播并覆盖 CSS(也需要垂直滚动条)

java - 无法解析类或包 'h2'

java - 使用 <T> 的通用方法调用