【问题标题】:Overloading constructor of child class [closed]子类的重载构造函数[关闭]
【发布时间】:2020-01-28 15:39:07
【问题描述】:

比如说我有一个Circle 类:

static final double DEFAULT_RADIUS = 1.0;

Circle(Point centre, double radius) {
    this.centre = centre;
    this.radius = radius;
}

Circle(Point centre) {
    this(centre, Circle.DEFAULT_RADIUS);
}

// ...

然后在ColoredCircleCircle的子类:

ColoredCircle(Point centre, Color color, double radius) {
    super(centre, radius);
    this.color = color;
}

ColoredCircle(Point centre, Color color) {
    // ???
}

ColoredCircle 的第二个构造函数应该输入什么?

  • this(centre, color, Circle.DEFAULT_RADIUS);
  • super(centre, Circle.DEFAULT_RADIUS); this.color = color;

我认为任何一个都可以,但哪个会产生“更干净的代码”?

【问题讨论】:

  • 如果不使用继承而使用接口,生活可能会更轻松

标签: java inheritance this super


【解决方案1】:

您的两个示例都有些多余,因为Circle 已经有一个将半径设置为默认值的构造函数。

我建议你使用它,然后让你的构造函数像这样:

super(centre);
this.color = color;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多