When you create a new instance (a new object) of a class using the new
keyword,
a constructor for that class is called. Constructors are used to initialize
the instance variables (fields) of an object.
Constructors are similar to methods, but with some important differences.
this
),
or a call on the superclass constructor (using super
).
If the first line is neither of these, the compiler automatically
inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.
this()
- Calls another constructor in same class.
Often a constructor with few parameters will call a constructor with more
parameters, giving default values for the missing parameters.
Use this
to call other constructors in the same class.
super
. Use super
to
call a constructor in a parent class. Calling the constructor
for the superclass must be the
first statement in the body of a constructor.
If you are satisfied with the default constructor in the superclass,
there is no need to make a call to it because it will be supplied automatically.
this
constructor call
public class Point {
int m_x;
int m_y;
//============ Constructor
public Point(int x, int y) {
m_x = x;
m_y = y;
}
//============ Parameterless default constructor
public Point() {
this(0, 0); // Calls other constructor.
}
. . .
}
super
- The superclass (parent) constructorAn object has the fields of its own class plus all fields of its parent class,
grandparent class, all the way up to the root class Object
.
It's necessary to initialize all fields, therefore all constructors must be called!
The Java compiler automatically inserts the necessary constructor calls in
the process of constructor chaining, or you can do it explicitly.
The Java compiler inserts a call to the parent constructor (super
)
if you don't have a constructor call as the first statement of you constructor.
The following is the equivalent of the constuctor above.
//============ Constructor (same as in above example)
public Point(int x, int y) {
super(); // Automatically done if you don't call constructor here.
m_x = x;
m_y = y;
}
super
explicitlyNormally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
super
constructor call has no parameters).