gpt4 book ai didi

java - 在构造函数内部或外部设置字段有区别吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:57 26 4
gpt4 key购买 nike

public class Test {
int value = 100;
public Test() {

}
}

public class Test {
int value;
public Test() {
value = 100;
}
}

是等价的吧?为什么我宁愿做一个而不是另一个?显然,如果构造函数采用稍后提供给字段的参数是一个原因:

public class Test {
int value;
public Test(int value) {
this.value = value;
}
}

或者我可能需要做一些特殊的计算。

但如果我那样做,还有其他充分的理由吗?

最佳答案

嗯,这完全取决于您打算如何使用它。我假设您不打算将 value 设置为静态,但它仅供内部使用。

首先让我们看一下字节码。

D:\eclipse\workspace\asdf\bin>javap -c A.class
Compiled from "A.java"
public class A {
int value;

public A();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 100
7: putfield #12 // Field value:I
10: return
}

D:\eclipse\workspace\asdf\bin>javap -c B.class
Compiled from "B.java"
public class B {
int value;

public B();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 100
7: putfield #12 // Field value:I
10: return
}

D:\eclipse\workspace\asdf\bin>

你猜怎么着?完全相同的!为什么?因为在使用 new 关键字创建对象之前,您不能使用值。

oracle docs指出:

As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast {
// initialize to 10
public static int capacity = 10;

// initialize to false
private boolean full = false;
}

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

现在您已经确认在构造函数中执行此操作的全部意义在于,如果您正在执行一些复杂的操作(例如初始化数组),否则请在声明字段时随意执行此操作。

如果您要使用 static 那么您显然在做两件不同的事情。这几乎就像检查是否有人曾经创建过该对象的实例一样。在有人创建对象之前,您的变量将是 0,之后它将是 100

关于java - 在构造函数内部或外部设置字段有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com