gpt4 book ai didi

java - 在抽象父类中重写 toString() 是个好主意吗?

转载 作者:行者123 更新时间:2023-12-01 16:45:11 25 4
gpt4 key购买 nike

我有两个如下所示的类,但是将 toString() 显式放入 abstract parent 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";
}
}

最佳答案

根据您试图在父类中定义的内容(只是概念、一些基本属性、一些常见行为),您可以做多种事情。正如 @Joakim Danielson 所说,如果您将其声明为 abstract它强制非抽象子类实现它,这可能会导致您在其toString()中重复一些类似的代码。实现。在许多情况下,您想要 toString()列出属性及其值(可能全部位于父类的域中,可能隐藏为 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

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

//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

关于java - 在抽象父类中重写 toString() 是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com