Tuesday, June 15, 2010

Constructors of Extended Classes

  • The constructor of the super class can be invoked.
  • Super(...) must be the first statement.
  • If the super constructor is not invoked explicitly, by default the no-arg super() is invoked implicitly.
  • You can also invoke another constructor of the same class.

public class ColoredPoint extends Point {
public Color color;
public ColoredPoint(double x, double y,
Color color) {
super(x, y);
this.color = color;
}
public ColoredPoint(double x, double y) {
this(x, y, Color.black); // default value of color
}
public ColoredPoint() {
color = Color.black;
}
}


Default Constructor of Extended Classes

Default no-arg constructor is provided:
public class Extended extends Super {
public Extended() {
super();
}
// methods and fields
}

Execution Order of Constructors

public class Super {
int x = ...; // executed first
public Super() {
x = ...; // executed second
}
// ...
}
public class Extended extends Super {
int y = ...; // executed third
public Extended() {
super();
y = ...; // executed fourth
}
// ...
}

No comments:

Post a Comment