Simple definition of constructor:
Special methods that initialize an object of a class. Always and only used together with the new
keyword to create an instance of a class.
- Has the same name as the name of the class.
- Can take one or more arguments.
- Has no return value, not even void.
- Default constructor takes no parameters.
- More than one constructor exist (method overloading).
but why use constructor initialization if it automatically done by
compiler !
Constructors initialize by the compiler (default constructor) if you have not implemented a constructor.
So why do we need to implement a constructor?
- Its job is to tell all of the local variables their initial values,
and possibly to start off another method within the class to do
something more towards the purpose of the class.
- Depends on what data you have, i.e. what is available.
- Different ways of creating an object.
- All class variables have to be initialized with the constructor.
As a example:
Consider the Rectangle
class in the java.awt
package which provides several different constructors, all named Rectangle()
, but each with a different number of arguments, or different types of arguments from which the new Rectangle
object will get its initial state. Here are the constructor signatures from the java.awt.Rectangle
class:
public Rectangle()
public Rectangle(int width, int height)
public Rectangle(int x, int y, int width, int height)
public Rectangle(Dimension size)
public Rectangle(Point location)
public Rectangle(Point location, Dimension size)
public Rectangle(Rectangle r)
What if your member variables are private
(security reasons)? If you do not want to give other classes to handle member variables, you have to use getters and setters, but in the first place, you can initialize it with a constructor, then you can change it using getters and setters later on when you need to change/update it.