david blaine
david blaine

Reputation: 5937

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

Upvotes: 2

Views: 107

Answers (2)

Daniel Imms
Daniel Imms

Reputation: 50189

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. Plus the constructor is much nicer than using static methods.

Upvotes: 2

Nathan White
Nathan White

Reputation: 1080

Personally, instead of having the getInt(), I would just initialise it in the constructor.

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.

Upvotes: 2

Related Questions