TVK practice example, not a SEBI question
Phase I IT paper: Programming Concepts (30 marks)
Tests: Constructors, inheritance, binding of variables and functions
What does this Java program print? In the options, / marks a new line.
class Base {
int x = 1;
Base() { show(); }
void show() { System.out.println("Base " + x); }
}
class Child extends Base {
int x = 2;
Child() { show(); }
@Override
void show() { System.out.println("Child " + x); }
}
public class Main {
public static void main(String[] args) {
Base b = new Child();
System.out.println(b.x);
}
}- Base 1 / Child 2 / 2
- Child 2 / Child 2 / 1
- Child 0 / Child 2 / 1
- Base 1 / Child 2 / 1
- Child 0 / Child 2 / 2
Answer: option (3)
- new Child() runs Base's constructor first, and that constructor calls show().
- Methods bind to the real object, so Child's show() runs. Child's own x = 2 has not been assigned yet, so x still holds the default 0. The first line is Child 0.
- Back in Child's constructor, x is now 2. The second line is Child 2.
- Fields do not override. b is declared as Base, so b.x reads Base's field. The third line is 1.
Output from a real run on OpenJDK 21
Child 0
Child 2
1