子类的重载构造函数

问题描述 投票:2回答:1

例如,我有一个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);
}

// ...

然后在ColoredCircle中,为Circle的子类:

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

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

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

  • ColoredCircle
  • this(centre, color, Circle.DEFAULT_RADIUS);

我认为任何一种都可以,但是会导致“更干净的代码”?

java inheritance this super
1个回答
0
投票

您的两个示例都有点多余,因为super(centre, Circle.DEFAULT_RADIUS); this.color = color;已经具有将半径设置为默认值的构造函数。

我建议您使用它,并像这样构造您的构造函数:

Circle
© www.soinside.com 2019 - 2024. All rights reserved.