Prev | Next |
Defining constructors
Initializing attributes
Constructors are special methods to initizalize an object while it comes into existence. During instantiation of a class the constructor gets automatically invoked. Values of few attributes may be known during instantiation and can be assigned. Thus a separate call to one or more setters can be avoided.
Constructor(s) bears the same name as that of the class.
// Point.java public class Point { private int x; private int y; public Point(int xInit, int yInit) { // Constructor this.x = xInit; this.y = xInit; } public void setX(int xCoord) { this.x = xCoord; } public void setY(int yCoord) { this.y = yCoord; } public int getX() { return this.x; } public int getY() { return this.y; } public void print() { System.out.println("(" + this.x + "," + this.y + ")"); } }
One may now instantiate (without calling setters) and print immediately. The effect is the same.
Point p2 = new Point(4,5); p2.print();
There are a few points to note here.
1. Use of constructor(s) do not make setters redundant. Setters may still be necessary for later modification of attributes.
2. Constructors don't return anything. In fact they don't have to, since their purpose is to initialize the attributes. Not to operate on them or retrieve them.
Exercise: Implement Driver2.java and use constructor to intitialize instead of setters. (Don't delete or modify Driver.java. Let it remain. Each driver is a test case that tests some part of your code.)
Default Constructor
A default constructor is one that does not take any arguments. It is usually used to assign default values to one or more attributes. For example,
Point() { // default constructor this.x = 0; // denotes origin this.y = 0; }
You can now check this in the driver code as follows. Output of this code will be (0,0). Again, write a separate driver class to check this new code.
Point p0 = new Point(); p0.print();
Note that we now have two constructors. Is this valid?
There is no harm in having more than one constructor. In fact, this is a feature of Java called method overloading (polymorphism is a broader term).
The correct method is invoked based on its signature. A method signature is characterized by the number and the type of arguments. Multiple methods or constructors can have the same name provided the number or type of arguments are different.
It is an healthy practice to define constructors, getters, setters before adding features to the class. Defining print methods helps in debugging errors during implementation.
Unlike C++, no explicit destructors needs to be defined. JVM takes care of cleaning up the unused objects (garbage collector).