Reputation: 499
I have searched about this lot and get this answer on stack overflow given answer here
But I want Answer of this
Upvotes: 1
Views: 1641
Reputation: 22437
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.
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?
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.
Upvotes: 5
Reputation: 528
To create a new object,we have to run the constructor.If we create default constructor compiler automatically add default constructor.But when we want to run paramaetrized constructor we have to define in the class..
Upvotes: 1