Akash  Singh Sengar
Akash Singh Sengar

Reputation: 499

why constructor use, why not always use simple initialization of variables?

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

Answers (2)

Blasanka
Blasanka

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.

  1. Has the same name as the name of the class.
  2. Can take one or more arguments.
  3. Has no return value, not even void.
  4. Default constructor takes no parameters.
  5. 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.

Upvotes: 5

Chamina Sathsindu
Chamina Sathsindu

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

Related Questions