这两种方法都有什么优势吗?
示例1:
class A {
B b = new B();
}
示例2:
class A {
B b;
A() {
b = new B();
}
}
这两种方法都有什么优势吗?
示例1:
class A {
B b = new B();
}
示例2:
class A {
B b;
A() {
b = new B();
}
}
当前回答
第二个例子是惰性初始化。第一个是更简单的初始化,它们本质上是一样的。
其他回答
There is one more subtle reason to initialize outside the constructor that no one has mentioned before (very specific I must say). If you are using UML tools to generate class diagrams from the code (reverse engineering), most of the tools I believe will note the initialization of Example 1 and will transfer it to a diagram (if you prefer it to show the initial values, like I do). They will not take these initial values from Example 2. Again, this is a very specific reason - if you are working with UML tools, but once I learned that, I am trying to take all my default values outside of constructor unless, as was mentioned before, there is an issue of possible exception throwing or complicated logic.
我在回复中没有看到以下内容:
在声明时进行初始化的一个可能的优势可能是,在当今的IDE中,您可以非常容易地跳转到变量的声明(大多数情况下) Ctrl-<hover_over_the_variable>-<left_mouse_click>)在你的代码中的任何地方。然后立即看到该变量的值。否则,你必须“搜索”初始化完成的位置(主要是:构造函数)。
这个优势当然是次要的,所有其他逻辑推理,但对一些人来说,“特征”可能更重要。
第二个例子是惰性初始化。第一个是更简单的初始化,它们本质上是一样的。
我个人的“原则”(几乎从未被打破)是:
的开头声明所有变量 一块 使所有变量为final,除非它们 不能 每行声明一个变量 永远不要在某处初始化变量 宣布 只初始化a中的东西 构造函数时使用 的构造函数 初始化
我的代码是这样的:
public class X
{
public static final int USED_AS_A_CASE_LABEL = 1; // only exception - the compiler makes me
private static final int A;
private final int b;
private int c;
static
{
A = 42;
}
{
b = 7;
}
public X(final int val)
{
c = val;
}
public void foo(final boolean f)
{
final int d;
final int e;
d = 7;
// I will eat my own eyes before using ?: - personal taste.
if(f)
{
e = 1;
}
else
{
e = 2;
}
}
}
This way I am always 100% certain where to look for variables declarations (at the start of a block), and their assignments (as soon as it makes sense after the declaration). This winds up potentially being more efficient as well since you never initialize a variable with a value that is not used (for example declare and init vars and then throw an exception before half of those vars needed to have a value). You also do not wind up doing pointless initialization (like int i = 0; and then later on, before "i" is used, do i = 5;.
我非常重视一致性,所以遵循这个“规则”是我一直在做的事情,它使处理代码变得更容易,因为你不需要到处寻找东西。
你的里程可能会有所不同。
class MyClass extends FooClass {
String a = null;
public MyClass() {
super(); // Superclass calls init();
}
@Override
protected void init() {
super.init();
if (something)
a = getStringYadaYada();
}
}
关于以上,
String a = null;
Null init可以避免,因为它是默认值。 然而,如果您需要另一个默认值, 然后,由于初始化顺序不受控制, 我将修改如下:
class MyClass extends FooClass
{
String a;
{
if( a==null ) a="my custom default value";
}
...