Why use a constructor, why not always use simple variable initialization?
I have searched this batch and am getting this answer on Stack Overflow given answer here
- Indicates that we can use both a constructor and simple initialization
But I want to answer this
- but why use constructor initialization if it is automatically executed by the compiler!
source to share
Simple constructor definition:
Special methods that initialize the class object. Always and only together with the keyword new
, an instance of the class is created.
- Has the same name as the class name.
- It can take one or more arguments.
- Has no return value, not even empty.
- The default constructor has no parameters.
- There is more than one constructor (method overload).
but why use constructor initialization when it is automatically executed by the compiler!
Constructors are compiler-initialized (default constructor) if you haven't implemented a constructor.
So why do we need to implement a constructor?
- Its job is to tell all local variables their initial values, and perhaps start another method inside the class to do something more towards the class.
- Depending on what data you have, i.e. what's available.
- Various ways to create an object.
- All class variables must be initialized with a constructor.
As an example:
-
Consider a class
Rectangle
in a packagejava.awt
that provides several different constructors, all namedRectangle()
, but each with a different number of arguments or different types of arguments, from which the newRectangle
object will receive its initial state. Here are the signatures of the constructor from thejava.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 the member variables are private
(security reasons)? If you don't want other classes to handle member variables, you need to use getters and setters, but first of all you can initialize it with the constructor, after which you can change it with getters and setters later when you need to change / updates.
source to share