[英]Proper variable initialization and call from another class
I have these two examples below:我在下面有这两个例子:
Example 1:示例 1:
public class class1{
private classN var1;
public class1(param1) {
var1 = new classN(param1); //here I initialize var1;
}
public void setVar1(param1){
this.var1 = new classN(param1)
}
public classN getVar1(){
return this.var1;
}
}
public class class2{
private class1 c1;
public class2(param) {
this.c1 = new class1(param);
}
public void handle(){
c1.setVar1(sth);
}
}
example 2:例子2:
public class class1{
private classN var1; //var1 not initialized inside constructor
public class1() {}
public void setVar1(param1){
this.var1 = new classN(param1);
}
public classN getVar1(){
return this.var1;
}
}
public class class2{
private class1 c1;
public class2() {
this.c1 = new class1();
}
public void handle(){
c1.setVar1(sth);
}
}
I want to ask 2 things:我想问两件事:
Thank you in advance.先感谢您。
class1
cannot be instantiated without it.在示例一中,变量在构造时初始化,没有它就不能实例化class1
。 In example 2, the variable is not initialized and is given the default value of null
until it is set at some later time setVar1
在示例 2 中,变量未初始化并被赋予默认值null
直到稍后设置setVar1
getVar1
before you call handle
, you will get the default null
value.如果你试图调用getVar1
打电话之前handle
,你会得到默认null
值。Are both examples equal?两个例子是否相等?
No, In case -1 , new class1(param);
不,在 -1 的情况下, new class1(param);
initializes var1;
初始化var1;
( to a non-null value), in second case, var1
will be null
. (到非空值),在第二种情况下, var1
将为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.