简体   繁体   中英

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?

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.

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.

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.

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

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.

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.

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

}

您可以两种方式创建对象,我建议您使用

JButton start = new JButton("Start");

最好的方法是在类的构造函数中创建和初始化对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM