Java OCA OCP Practice Question 3203

Question

What will be written to the standard output when the following program is run?

class Shape {
  int i;//w  w  w.j av  a  2  s.com
  Shape() { add(1); }
  void add(int v) { i += v; }
  void print() { System.out.println(i); }
}

class Rectangle extends Shape {
  Rectangle() { add(2); }
  void add(int v) { i += v*2; }
}

public class Main {
  public static void main(String[] args) {
    bogo(new Rectangle());
  }

  static void bogo(Shape b) {
    b.add(8);
    b.print();
  }
}

Select the one correct answer.

  • (a) 9
  • (b) 18
  • (c) 20
  • (d) 21
  • (e) 22


(e)

Note

An object of the class Rectangle is created.

The first thing the constructor of Extension does is invoke the constructor of Shape, using an implicit super() call.

All calls to the method void add(int) are dynamically bound to the add() method in the Rectangle class, since the actual object is of type Rectangle.

Therefore, this method is called by the constructor of Shape, the constructor of Rectangle, and the bogo() method with the parameters 1, 2, and 8, respectively.

The instance field i changes value accordingly: 2, 6, and 22.

The final value of 22 is printed.




PreviousNext

Related