matua
matua

Reputation: 627

Initialization of Class fields

public class InitializationTest {
    private int x;
    private int y;
    private int sumOFXandY = x + y;

    public InitializationTest(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getSumOFXandY() {
        return sumOFXandY;
    }
}

class Tester {
    public static void main(String[] args) {
        InitializationTest initializationTest = new InitializationTest(5, 6);
        System.out.println(initializationTest.getX());
        System.out.println(initializationTest.getY());
        System.out.println(initializationTest.getSumOFXandY());
        System.out.println(initializationTest.getX() + initializationTest.getY());
    }
}

 Output:
 5
 6
 0 //Why not 11?
 11

In the example above my brain cannot understand such simple thing - a revelation.

When the class is created, its fields are initialized with default values. In this case those are 0.

Upon calling the constructor x is initialized with 5 and y is initialized with 6. Why then sumOFXandY is somewhere aside and still is initialized with 0 even after calling the constructor. Why is not it initialized with 5 + 6 = 11 ?

Upvotes: 0

Views: 36

Answers (1)

Thiyagu
Thiyagu

Reputation: 17920

Because it(sumOFXandY) cannot be re-initialized after the constructor gets executed. When you create an object, it initializes the instance variables that are initialized inline (here it is sumOFXandY = x + y). Then the constructor block gets executed.

To solve this, move sumOFXandY = x + y inside the constructor.

Upvotes: 1

Related Questions