我有两个类似下面的类,但是将toString()
显式放入abstract
parent class
是个好主意,还是应该在parent class
中省略它,而override
直接在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";
}
}
答案 0 :(得分:3)
根据您要在父类中定义的内容(只是概念,一些基本属性,一些常见行为),您可以做很多事情。正如@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
答案 1 :(得分:2)
在声明abstract
时,您将强制Shape
的子类来实现它,否则它是可选的。因此,如果需要,toString
是必不可少的工具。
当然,不能保证在子子类中实现它。