[英]Is it a good idea to override toString() in an abstract parent class?
我有两个如下所示的类,但是将toString()
显式地放入abstract
parent class
还是一个好主意,还是应该在parent class
忽略它而直接在child class
override
?
//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()
。
//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
强制性的工具。
当然,不能保证在子子类中实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.