OCA Java SE 8 Mock Exam 2 - OCA Mock Question 30








Question

What is the output of the following code?

class Shape {
  void print() {
    System.out.println("Shape");
  }
}

class Rectangle extends Shape {
  void print(int a) {
    System.out.println("Rectangle");
  }
}

class Square extends Shape {
  void print() {
    System.out.println("Square");
  }
}

public class Main {
  public static void main(String args[]) {
    Shape shape = new Rectangle();
    Square rabbit = new Square();
    shape.print();
    rabbit.print();
  }
}

    a  Shape 
       Square 

    b  Rectangle 
       Square 

    c  Shape 
       Shape 

    d  None of the above 




Answer



A

Note

The class Rectangle doesn't override the method print() defined in the class Shape.

The class Rectangle defines a method parameter with the method print, which makes it an overloaded method, not an overridden method.

Because the class Rectangle extends the class Shape, it has access to the following two overloaded print methods:

void print() { System.out.println("Shape"); } 
void print(int a) { System.out.println("Rectangle"); } 

The following line of code creates an object of class Rectangle and assigns it to a variable of type Shape:

Shape shape = new Rectangle(); 

When you call the method print on the previous object, it executes the method print, which doesn't accept any method parameters, printing the following value:

Shape

The following code will also print Shape and not Rectangle:

Rectangle shape = new Rectangle(); 
shape.print(); 
class Shape {//from   w  w w. j  a va2s .co  m
  void print() {
    System.out.println("Shape");
  }
}

class Rectangle extends Shape {
  void print(int a) {
    System.out.println("Rectangle");
  }
}

class Square extends Shape {
  void print() {
    System.out.println("Square");
  }
}

public class Main {
  public static void main(String args[]) {
    Shape shape = new Rectangle();
    Square rabbit = new Square();
    shape.print();
    rabbit.print();
  }
}

The code above generates the following result.