簡體   English   中英

在抽象父類中重寫toString()是個好主意嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM