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 } }

-------------Problems Reply------------

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.

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

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

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.

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

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,

Category:java Views:0 Time:2010-10-13
Tags: java

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.256 (s). 11 q(s)