Eugene
Eugene

Reputation: 60184

Why should I use constructor if I can initialize instance variable another way

Why should I use constructor to initialize instance variables while it is possible at the point of their declaration?

class Frog {
     public int x = 4;
     Frog() { // Why should I use you }
}

Upvotes: 2

Views: 4079

Answers (6)

shweta sareen
shweta sareen

Reputation: 11

We need a constructor to increase flexibility with which we can initialize objects. We can initialize all variables of objects at one go and with any value at any time. By initializing we bind that value to a variable. Also if need arises to initialize a variable permanently,one can achieve that with final keyword before variable initialization.

Upvotes: 1

maxim_ge
maxim_ge

Reputation: 1263

My five cents. Sometimes it's needed to introduce few constructors, they initialize variables differently.

Upvotes: 0

duffymo
duffymo

Reputation: 308753

Because constructors of a class should fully initialize a class, and users should have the opportunity to set that value if they wish.

So your class should be:

class Frog 
{
    public static final int DEFAULT_VALUE = 4;

    private int x;

    Frog() { this(DEFAULT_VALUE) }
    Frog(int x) { this.x = x; }
}

Upvotes: 3

VoteyDisciple
VoteyDisciple

Reputation: 37803

If the only initializations you need are of the public int x = 4 variety, you do not need a constructor.

You need a constructor if the initialization you're doing is more complex than that. Perhaps you need to open a database connection. Or perhaps (more simply) the value of x is going to be supplied by the instantiating method at the time of construction. For example: Frog f = new Frog(4);

Upvotes: 6

Emerion
Emerion

Reputation: 810

U Can use a constructor to fill private data of that object. Because if x isn't public, you wouldn't be able to access it. Offcourse when both are public, you can use the constructor to place all the initializing in one place, which makes it easier to read by colleagues,

Upvotes: -2

user151323
user151323

Reputation:

You should use me because I will help you keep your initializations in one place. Because it will help you other colleagues to know where to expect initializations and not miss one if they're scattered aroudn the code.

Upvotes: 9

Related Questions