本文介绍了应该在类或构造函数中初始化成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
初始化变量(尤其是在类级别的对象引用)是一种好习惯吗?请考虑以下示例;
Is it a good practice to initialize variables, specially object references at class level?Please consider the following examples;
public class MyClass {
private static MyObject myObject;
public static void main(String[] args) {
myObject = new MyObject();
}
}
或
public class MyClass {
private MyObject myObject = new MyObject();
public static void main(String[] args) {
// Other code
}
}
哪种方法最好?请向我介绍两者的优缺点.
Which way is best? Please guide me about the pros and cons of both.
致谢.
推荐答案
通常,由于对象的寿命(可能)较短,因此首选惰性实例化(第一个代码段).您应该支持尽可能短的对象生命期.
In general, lazy instantiation (the first snippet) is preferred since the object has a (potentially) shorter lifetime. You should favor the shortest object lifetime possible.
这篇关于应该在类或构造函数中初始化成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!