PoQ
PoQ

Reputation: 303

What is the proper way of creating objects in Java?

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?

Upvotes: 3

Views: 233

Answers (9)

Manas Mhade
Manas Mhade

Reputation: 20

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

Upvotes: -3

Mel
Mel

Reputation: 453

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.

Upvotes: 3

Ashwani Verma
Ashwani Verma

Reputation: 39

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

JButton start = new JButton("Start");

Upvotes: -1

Nithin Varghese
Nithin Varghese

Reputation: 258

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

Upvotes: 1

Loki
Loki

Reputation: 4130

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

}

Upvotes: 0

S. Pauk
S. Pauk

Reputation: 5318

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.

Upvotes: 0

antonio
antonio

Reputation: 18262

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.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234885

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.

Upvotes: 1

Puce
Puce

Reputation: 38152

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.

Upvotes: 3

Related Questions