简体   繁体   English

正确的变量初始化和从另一个类调用

[英]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:我想问两件事:

  1. Are both examples equal?两个例子是否相等?
  2. Is var1 initialized in both two cases or I will get some kind of exception in example 2? var1 是否在两种情况下都被初始化,或者我会在示例 2 中得到某种异常?

Thank you in advance.先感谢您。

  1. No, both examples are not equal.不,这两个例子并不相等。 In example one the variable is initialized at construction time and 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
  2. No, you will not get an exception.不,您不会得到例外。 If you try to call 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM