466,184 views
5 votes
5 votes
What is the output of the following program?

public class Test {
public static void main(String[] args) {
new A();
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;
}
}

User DVM
by
3.0k points

1 Answer

25 votes
25 votes

Answer:

i from A is 7

Step-by-step explanation:

Well when you invoke new B (), you got a superclass for that which is A's constructor, and it invokes first. So it displays i from A is 7

User Tomas Eglinskas
by
3.0k points