【问题标题】:Is it a good idea to override toString() in an abstract parent class?在抽象父类中重写 toString() 是个好主意吗?
【发布时间】:2018-11-03 07:54:05
【问题描述】:

我有两个类似下面的类,但是将toString() 明确放入abstract parent class 是一个好主意,或者我应该在parent classoverride 中直接在@987654326 中省略它@?

//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";
    }
}

【问题讨论】:

    标签: java inheritance abstract-class tostring


    【解决方案1】:

    根据您要在父类中定义的内容(只是概念、一些基本属性、一些常见行为),您可以做多种事情。正如@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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2010-11-05
        • 2016-06-20
        • 1970-01-01
        相关资源
        最近更新 更多