2

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 }
}
Eugene
  • 59,186
  • 91
  • 226
  • 333
  • 2
    possible duplicate of [Should I initialize variable within constructor or outside constructor](http://stackoverflow.com/questions/3918578/should-i-initialize-variable-within-constructor-or-outside-constructor) It feels like yesterday... :) – Colin Hebert Oct 13 '10 at 12:56

6 Answers6

9

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.

6

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);

VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
  • 3
    You're always going to have a constructor. If it doesn't find one, the compiler will generate an empty, no-argument constructor. – Powerlord Oct 13 '10 at 13:20
  • 2
    Yes, but what the compiler does is seldom of any interest to the developer. Whether you have to **write** a constructor is the question. I don't care if the compiler adds a nest of fruit flies to the bytecode if I don't have to write it. – VoteyDisciple Oct 13 '10 at 13:48
3

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; }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

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.

0

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

maxim_ge
  • 1,153
  • 1
  • 10
  • 18
-2

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,

Emerion
  • 820
  • 6
  • 13