192k views
1 vote
Analyze the following code:

public class Test {
public static void main(String[] args) {
new B();
}
}

class A {
int i = 7;

public A() {
setI(20);
System.out.println("i from A is " + i);
}

public void setI(int i) {
this.i = 2 * i;
}
}

class B extends A {
public B() {
// System.out.println("i from B is " + i);
}

public void setI(int i) {
this.i = 3 * i;
}
}


A. The constructor of class A is not called.
B. The constructor of class A is called and it displays "i from A is 7".
C. The constructor of class A is called and it displays "i from A is 40".
D. The constructor of class A is called and it displays "i from A is 60".

User Zastrowm
by
8.7k points

1 Answer

5 votes

Final Answer:

The constructor of class A is called and it displays "i from A is 40". The correct answer is C.

Step-by-step explanation:

In the given code, the main method creates an instance of class B using new B();. Class B extends class A, so when an object of class B is created, the constructor of class A is invoked before the constructor of class B. In class A's constructor, the method setI(20) is called, which sets the value of i to 2 * 20 = 40. Therefore, the output of the program will be "i from A is 40".

The commented-out line // System.out.println("i from B is " + i); in class B indicates that the constructor of class B does not explicitly print the value of i from class B. Thus, the output is solely based on the actions within the constructor of class A.

To summarize, the key point is that the constructor of class A is indeed called, and the value of i is modified to 40 within that constructor. The constructor of class B does not alter the output in this case, so the correct answer is option C.

User Munch
by
8.7k points