143k views
2 votes
What happen when a member is initialized in class declaration and constructor both? Consider the following program.

// filename: Test.java
public class Test
{
int x = 2;
Test(int i) { x = i; }
public static void main(String[] args) {
Test t = new Test(5);
System.out.println("x = " + t.x);
}
}

User Ethan Long
by
8.5k points

1 Answer

3 votes

Final answer:

When a class member variable is initialized both in the class declaration and the constructor, the constructor's initialization takes precedence. In the provided Java code example, the field 'x' is first set to 2, and then overridden to 5 by the constructor.

Step-by-step explanation:

When a member is initialized in both the class declaration and the constructor, the initialization at the class level happens first, and then the constructor's initialization takes place after that. In the provided code snippet, the field x is initially set to 2 during the class level initialization. Then, when the Test object is created using the constructor Test(5), the constructor sets the field x to the value passed, which is 5.

The main method creates an instance of Test and initializes x with the constructor's argument 5, overriding the initial value of 2. Therefore, when System.out.println is called, it prints x = 5, indicating that the constructor's assignment takes precedence over the class declaration initialization.

User Ircbarros
by
8.0k points