40.7k views
3 votes
Analyze the following code:

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

class A {
int i = 7;

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

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

class B extends A {
public B() {
setI(20);
// 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".

1 Answer

5 votes

Final answer:

Class A's constructor is called when an instance of class B is created, and it displays B. the initial value of 'i' from class A, which is 7.

Step-by-step explanation:

The code you've given is an example of inheritance in Java, where class B extends class A. When an instance of class B is created (using new B();), the constructor of its superclass (class A) is automatically called before class B's constructor executes. Since class A's constructor print statement (System.out.println("i from A is " + i);) occurs before class B has a chance to change the value of i, it will display the initial value of i set in class A, which is 7. Therefore, when the new B(); line is run, the constructor of class A is called and displays "i from A is 7". At this point, the value of i is not yet modified by class B's setI() method because A's constructor finishes executing before the setI() method is called.

The setI method in class B assigns the value 3 * i to the variable i. In this case, i is 20, so i becomes 60. Therefore, when the constructor of class A prints the value of i, it displays "i from A is 40".

User Siannopollo
by
8.0k points