在构造函数内部或外部设置字段是否有区别? [英] Is there a difference in setting fields inside or outside the constructor?

查看:133
本文介绍了在构造函数内部或外部设置字段是否有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

    }
}

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

是等价的,对吗?我有理由为什么喜欢做另一个?显然,如果构造函数接受后来赋予字段的参数是一个原因:

Are equivalent, right? Is there a reason why I'd prefer to do one over the other? Obviously if the constructor takes parameters that are later given to the fields is a reason:

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

或许我需要做一些特别的计算。

Or perhaps I need to do some special calculation.

但如果我这样做,还有另一个好理由吗?

But if I don't do that, is there another good reason?

推荐答案

这一切都取决于你打算如何使用它。我将假设您不打算将设置为静态,但它仅用于内部目的。

Well it all really depends on how you plan on using this. I'm going to assume that you don't plan to make value static but it's just there for internal purposes.

首先让我们看看字节码。

Firstly lets look at the bytecode.

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 关键字创建对象之前不能使用值。

Guess what? Exactly the same! Why? Because you can't USE value until you make an object by using the new keyword.

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




当初始化值可用时,这种方法很有效初始化可以放在
一行。但是,这种形式的初始化具有局限性,因为其简单性为
。如果初始化需要一些逻辑(例如,
错误处理或for循环来填充复杂数组),简单的
赋值是不合适的。实例变量可以在
构造函数中初始化,其中可以使用错误处理或其他逻辑。
为类变量提供相同的功能,Java编程
语言包括静态初始化块。

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.

所以现在你已经确认在构造函数中完成这一操作的全部意义在于你是在做一些复杂的事情,比如初始化一个数组,否则你可以在声明字段时自由地执行它。

So now you have confirmation that the whole point of doing it in the constructor is if you are doing something complex like initializing an array otherwise feel free to do it right there when you declare the field.

如果您要使用 static ,那么您显然会做两件事。这几乎就像是检查某人是否曾创建过这个对象的实例。你的变量将是 0 ,直到有人创建一个对象,然后它将是 100

If you WERE to use static then you are obviously doing two different things. It's almost like a check to see if someone has ever created an instance of this object or not. Your variable would be 0 until someone creates an object and then it would be 100 afterward.

这篇关于在构造函数内部或外部设置字段是否有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆