3

Which method is better? Creating objects in class constructor:

public class Menu {
 private JButton start;
 // ...
 public Menu() {
  start = new JButton("Start");
  // ...
 }
}

or creating objects while variable declaration?:

public class Menu{
 private JButton start = new JButton("Start");
 // ...
 public Menu(){
  // ...
 }
}

and what is the difference?

PoQ
  • 304
  • 3
  • 15

9 Answers9

3

Both variants are OK , but I prefer the second one since there's one statement less - to write, but more important to read and to maintain.

There is no runtime difference in this case, AFAIK.

Sometimes, when following the second variant, you can even remove the custom contructor altogether.

Puce
  • 37,247
  • 13
  • 80
  • 152
  • I agree. and you don't have to hunt or search for the declaration in the code, you see it immediately. – Ascalonian Mar 19 '15 at 12:23
  • Wouldn't the first case have the advantage of lazily instantiating the button object? – Chetan Kinger Mar 19 '15 at 12:28
  • 1
    @bot I don't know what you mean. Lazy initialization would be a third variant. You could turn both variants into lazy ones by moving the initialization code code from the constructor/ declaration to another method, which is not called by the constructor (directly or indirectly). – Puce Mar 19 '15 at 12:34
  • @Puce It is my understanding that the button object will not be created until the menu object is created. If that's not the case, then I stand corrected. – Chetan Kinger Mar 19 '15 at 16:00
  • @bot This statement is corret. But how is it related to your previous comment? – Puce Mar 19 '15 at 16:03
  • @Puce That's what I meant by lazily instantiating the button. – Chetan Kinger Mar 19 '15 at 16:06
  • @bot In both variants the "button object will not be created until the menu object is created". None of them uses lazy initialization however. In both variants the initialization of the button happens at the time when the menu gets initialized. Please check about lazy initialization, eg. here: https://en.wikipedia.org/wiki/Lazy_initialization – Puce Mar 19 '15 at 16:09
  • @Puce That's right. I should elaborate my thoughts. What I meant was that until and unless there is a need to create a Menu object, the button object will not be created. If Menu provides some static methods, it might not need to be instantiated thus delaying the creation of the button instance until a menu actually needs to be created. – Chetan Kinger Mar 19 '15 at 16:15
  • @bot Please not that in **both** variants button is an instance variable, not a static variable. – Puce Mar 19 '15 at 16:26
  • @Puce I am not sure why I assumed it was static. You are right then. There is no difference in both cases. Only when the reference is static is when it will be created at class load time. My bad. – Chetan Kinger Mar 19 '15 at 16:30
3

Already answered here , The question was for C#, but the logic is still the same.

It is said to follow these rules, which are pretty complete:

1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).

2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.

3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.

4. Be consistent in your practice. (the most important rule)

Read the comments for more details.

Community
  • 1
  • 1
Mel
  • 453
  • 1
  • 4
  • 14
1

Initialisation within the constructor does allow you to deal easily with exceptions, which can be helpful as your code base matures.

But some folk say that declaration at the point of initialisation is more readable. But then the order that fields appear in the source becomes important.

Aside from the exception consideration, it's down to personal opinion.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

The second method is better.

There are four different ways to create objects in java:

A. Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way.

MyObject object = new MyObject();

B. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("com.sample.MyObject").newInstance();

C. Using clone() The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject(); MyObject object = anotherObject.clone();

D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject();

Nithin Varghese
  • 258
  • 3
  • 12
  • The question was not about which different methods exist, but about which one is "the proper way", and "what is the difference". You did not answer the second one at all, and you answered the first one in one sentence without even explaining it, which does not make your answer very useful. Consider re-reading the question and trying to answer the specific point that was asked (and explain your answer, so OP and future readers can learn from it) – LionC Mar 19 '15 at 12:57
0

There is no difference. I usually prefer to use the second way, but if you need to have exception handling, then you need to use the first way.

antonio
  • 18,044
  • 4
  • 45
  • 61
0

With the first option you could add more logic to object initialization (exception handling, logging, etc..).

NOTE: if you would like to consider Dependency Injection at some point then initialization on declaration is not an option.

S. Pauk
  • 5,208
  • 4
  • 31
  • 41
0

You can create objects in different ways. As Neeraj already said Lazy Initialization can sometimes be the preferred way.

In your example, where you need your button as soon as the parent Object is instantiated, you can use both ways.

But you can also consider the following example, where you create the child object exactly at the time you need it.

public class MyObject{
    private List<String> myList = null;

    public MyObject(){
        //do whatever you want
    }

    public void add(String toAdd){
        if(myList == null){
            myList = new ArrayList<String>();
        }
        myList.add(toAdd);
    }

}
Loki
  • 4,065
  • 4
  • 29
  • 51
-1

You can craete object both way and i recommend you to use

JButton start = new JButton("Start");
Ashwani Verma
  • 39
  • 1
  • 11
-3

Best way is to create and initialize object in the constructor of a class.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
  • In this form, the answer is not very useful, as you are not explaining your answer, denying OP and future readers the possibility to learn from it(I did not downvote btw) – LionC Mar 19 '15 at 12:55