简体   繁体   English

用这种方式初始化非静态成员变量是否会有任何问题?

[英]Will there any issues in initializing non-static member variables this way?

I have initialized the variables as follows in the code below. 我已经在下面的代码中初始化了变量。 Is it okay to initialize like this ? 这样初始化可以吗?

public class StaticInit {

    int x = getInt();
    String z = "Lucky Number " + processInt(x);

    public static int getInt() {
        int ret = 10;
        System.out.println("ret- " + ret);
        return ret;
    }

    public static int processInt(int toProcess) {
        int toRet = toProcess / 2;
        System.out.println("toRet- " + toRet);
        return toRet;
    }

    public static void main(String[] args) {
        StaticInit sit = new StaticInit();
    }
}

You can initialise with the variable declaration or in the constructor. 您可以使用变量声明或在构造函数中进行初始化。 Some will argue that one or the other is better but either works. 有人会争辩说,一个或另一个更好,但两者都能起作用。 I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases. 我相信在构造函数中进行初始化的理由是,所有变量初始化都在同一位置,因为在某些情况下,并非所有内容都可以在构造函数之外进行初始化。

public class StaticInit {

    int x = getInt();
    String z = "Lucky Number " + processInt(x);

}

or 要么

public class StaticInit {

    int x;
    String z;

    public StaticInit() {
        x = 10;
        z = x / 2;
    }
}

For this case in particular though , I would definitely recommend using the constructor since z relies on x . 但是对于这种情况,特别地 ,我绝对建议使用构造函数,因为z依赖于x Plus the constructor is much nicer than using static methods. 另外,构造函数比使用静态方法好得多。

Personally, instead of having the getInt() , I would just initialise it in the constructor. 就个人而言,我不用在getInt()初始化它,而是在构造函数中对其进行初始化。

Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value. 除非您要在外部使用getInt()函数,否则我看不到要使用它的意义,特别是因为它返回的是硬编码值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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