在抽象父 class 中覆盖 toString() 是个好主意吗?

Is it a good idea to override toString() in an abstract parent class?

我有两个 class 如下所示,但是将 toString() 显式放入 abstract parent class 是个好主意还是我应该在parent classoverride 直接在 child class?

//Parent class
public abstract class Shape {
    @Override
    public abstract String toString();
}

//Child class
public class Circle extends Shape {
    @Override
    public String toString() {
        return "This is a Circle";
    }
}

根据您要在父级 class 中定义的内容(只是概念、一些基本属性、一些常见行为),您可以做很多事情。正如@Joakim Danielson 所说,如果你将它声明为 abstract,它会强制非抽象子 classes 实现它,这可能会导致你在它们的 toString() 中重复一些类似的代码] 实施。在许多情况下,您希望 toString() 列出属性及其值(它们可能都在父 class 的域中,可能隐藏为 private),或者执行类似:

//Parent class
public abstract class Shape {
    protected abstract double surface();
    @Override
    public String toString() {
        return "I am a geometric shape and my surface is: " + surface();
    }
}

//Child class
public class Circle extends Shape {
    private double r;
    public Circle(double r) {
        this.r = r;
    }
    @Override
    public String toString() {
        return super.toString() + " and my radius is: " + r;
    }
    @Override
    protected double surface() {
        return r * r * Math.PI;
    }
}

//Main class
class Main {
    public static void main(String[] args) {
        Shape c = new Circle(2.0);
        System.out.println(c.toString());
    }
}

//Output
I am a geometric shape and my surface is: 12.566370614359172 and my radius is: 2.0

在这种情况下,您还可以扩展父 class 的功能。这样,您可以将一些预期的常见行为移动到父 class 级别,并且它使您能够在不需要添加的 class 中不实现 toString()更多信息。

//Child class
public class Square extends Shape {
    private double a;
    public Square(double a) {
        this.a = a;
    }
    @Override
    protected double surface() {
        return a * a;
    }
}

//Main class
class Main {
    public static void main(String[] args) {
        Shape[] shapes = {new Circle(2.0), new Square(3.0)};
        for (Shape shape : shapes)
            System.out.println(shape.toString());
    }
}

//Output
I am a geometric shape and my surface is: 12.566370614359172 and my radius is: 2.0
I am a geometric shape and my surface is: 9.0

当你声明它时abstract你强制Shape的子类实现它,否则它是可选的。因此,如果您希望它成为强制性的 toString,它是一个工具。

当然不能保证在子类中实现。