Java Reference
In-Depth Information
3.2. Constructors in Extended Classes
An object of an extended class contains state variables (fields) that are
inherited from the superclass as well as state variables defined locally
within the class. To construct an object of the extended class, you must
correctly initialize both sets of state variables. The extended class's con-
structor can deal with its own state but only the superclass knows how to
correctly initialize its state such that its contract is honored. The exten-
ded class's constructors must delegate construction of the inherited state
by either implicitly or explicitly invoking a superclass constructor.
A constructor in the extended class can directly invoke one of the su-
perclass's constructors using another kind of explicit constructor invoc-
ation: the superclass constructor invocation, which uses the super con-
struct. This is shown in the first constructor of the ColorAttr class:
public ColorAttr(String name, Object value) {
super(name, value);
decodeColor();
}
This constructor passes the name and value up to the corresponding
two-argument superclass constructor. It then invokes its own decodeColor
method to make myColor hold a reference to the correct ScreenColor ob-
ject.
You can defer the choice of which superclass constructor to use by expli-
citly invoking one of your class's own constructors using this instead of
super , as shown in the second constructor of ColorAttr .
public ColorAttr(String name) {
this(name, "transparent");
}
 
Search WWH ::




Custom Search