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.
Example of explicit 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) constructor
An 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;
}
Why you might want to call super explicitly
Normally, 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.
- You want to call a parent constructor which has parameters (the
automatically generated
super constructor call has no
parameters).
- There is no parameterless parent constructor because only constructors
with parameters are defined in the parent class.
79 comments | | Score: 4
|