将值分配给类变量
我会尽量保持简单。
class MyClass {
private int x = 3;
}
vs.
class MyClass {
private int x;
public MyClass() {
x = 3;
}
}
两者之间有什么区别以及这些差异如何发挥作用?
提前致谢。
I'll try to keep this simple.
class MyClass {
private int x = 3;
}
vs.
class MyClass {
private int x;
public MyClass() {
x = 3;
}
}
What's the difference between the two and how do these differences come into play?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
与
is same as
这些都是一样的
但如果 x 是静态变量,它们就会不同。
These are both the same
But if x were a static variable, they would be different.
什么都没有。变量在调用构造函数时设置,您可以通过添加行
MyClass temp = new MyClass()
并使用调试器单步执行它来查看这一点,调试器将转到行private int x = 3;
首先。Nothing at all. Variable's are set when a constructor is called, you can see this by adding the line
MyClass temp = new MyClass()
and stepping into it with the debugger, the debugger will go to the lineprivate int x = 3;
first.字段的初始化是在调用构造函数之前完成的。但对于你的例子来说它们是相同的
Initialization of fields are done before constructor is called. But for your example they are same
在您的示例中,您实际上有实例变量,而不是类变量。
当您添加新的构造函数 MyClass(Object argument) 并忘记直接设置 x 并忘记调用原始的无参数构造函数时,差异就出现了。如果适用的话,将其定为最终版本当然会迫使您记住在某处设置值。
对于类变量,事情会变得更有趣,只需将 x 更改为 static 并将以下 main 方法添加到 MyClass 并观察结果。
In your example you actually have instance variable, not the class variable.
Difference comes in the moment when you add new constructor MyClass(Object argument) and forget to set x directly and forget to call original no-arg constructor as well. Making it final, if applicable, will of course force you to remember to set value somewhere.
In the case of class variable things get much more interesting, just change x to static and add following main method to the MyClass and observe results.
正如其他人提到的,它们都是等效的。主要区别在于代码的可读性、重复性和可维护性。如果我们将给定的示例扩展为具有多个构造函数,您将开始注意到差异。如果 x 的值不依赖于构造函数,我建议初始化字段变量,否则在构造函数中设置值。这将在一定程度上增加代码的可读性和可维护性,并删除重复的代码(在多个构造函数要使用相同值启动变量的情况下)。
As others has mentioned they both are equivalent. The main difference is the readability, duplicity and maintainability of the code. If we expand the given example to have more than one constructor you'll start to notice differences. If the value of x is not to depend on the constructor I'd recommend to initialize the field variable else set the value in the constructors. This will somewhat increase the readability and maintainability of the code and remove duplicated code (in the case were several constructors are to initiate the variable with the same value).