简体   繁体   English

在 Java 中创建对象的正确方法是什么?

[英]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.在这种情况下没有运行时差异,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.已经在这里回答,问题是针对C#的,但是逻辑还是一样的。

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...). 1.不要使用声明中的默认值(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. 2.如果您没有更改字段值的构造函数参数,则首选声明中的初始化。

3. If the value of the field changes because of a constructor parameter put the initialization in the constructors. 3.如果字段的值因构造函数参数而改变,则将初始化放在构造函数中。

4. Be consistent in your practice. 4.在你的实践中保持一致。 (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:在java中有四种不同的方式来创建对象:

A. Using new keyword This is the most common way to create an object in java. A. 使用 new 关键字 这是在 java 中创建对象最常见的方式。 Almost 99% of objects are created in this way.几乎 99% 的对象都是以这种方式创建的。

MyObject object = new MyObject(); MyObject 对象 = 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. B. 使用 Class.forName() 如果我们知道类的名称并且它有一个公共默认构造函数,我们可以通过这种方式创建一个对象。

MyObject object = (MyObject) Class.forName("com.sample.MyObject").newInstance(); 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. C. 使用 clone() clone() 可用于创建现有对象的副本。

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

D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form. D. 使用对象反序列化 对象反序列化只不过是从它的序列化形式创建一个对象。

ObjectInputStream inStream = new ObjectInputStream(anInputStream ); ObjectInputStream inStream = new ObjectInputStream(anInputStream); MyObject object = (MyObject) inStream.readObject(); MyObject 对象 = (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.正如 Neeraj 已经说过的, Lazy Initialization有时可能是首选方式。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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