Quazi Irfan
Quazi Irfan

Reputation: 2589

Traditional Practice to initialize the field members of a class

I come from C++ background, where the field of a class are initialized inside the constructor. But here is java I see that I can initialize then while declaring, which is different from C++.

So, I my question was which is the best/traditional practice to initialize the field members of any class. Is it...

( Because I of my background I am a little biased towards initializing field members inside of a constructor.)

Upvotes: 4

Views: 2417

Answers (4)

Oak Bytes
Oak Bytes

Reputation: 4795

Though there is no 'best practice' there are some situations where certain methods work best.

For example, if you have a simple initialization value, then you can do it along with declaration.

If you have complex initialization logic (e.g array initialization), it can go inside the constructor.

Initializer blocks (non-static scope) are useful if you want to share common initialization code across constructors.

You can look at following link for more details http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533520

You should write the code which appears to be the simplest and clearest. I prefer declaring and initialising a simple value in one line and breaking up more complex lines.

You might find this notiation interesting.

private final List<String> words = Arrays.asList("one", "two", "three");

or using double brace notation.

private final Map<String, Integer> map = new LinkedHashMap<String, Integer>() {{
    put("one", 1);
    put("two", 2);
    put("three", 3);
}};

Upvotes: 1

user7094
user7094

Reputation:

I don't think there is a 'best practice' for initializing member variables. Obviously in Java you can initialize them in the declaration which is fine, or you can do it from the constructor. Unless you need to do something complicated (i.e. obtain a reference to a DataSource or something like that which might only be available with arguments passed in to the constructor).

In other words, there isn't a 'right way' of doing it, consistency is probably more important.

That said, bear in mind that Java will initialise uninitialised member variables for you if you don't do it. e.g. int variables will be set to 0, boolean variables will be set to false, any objects will be set to null, etc.

Upvotes: 6

Jonas
Jonas

Reputation: 1234

Don't know if I get your question right but do you want to know how to initialize variables in a class?

    private String s;

public EditListener(String s){
    this.s = s;
}

Upvotes: 0

Related Questions