Search code examples
javainheritancethissuper

Overloading constructor of child class


Say for example I have a Circle class:

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);
}

// ...

Then in ColoredCircle, a child class of Circle:

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

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

What should go in for the second constructor of ColoredCircle?

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

I think either would work, but which would result in "cleaner code"?


Solution

  • Both of your examples are a bit redundant, since Circle already has a constructor that sets the radius to the default value.

    I'd suggest you use it, and just make your constructor like so:

    super(centre);
    this.color = color;