Java OCA OCP Practice Question 3086

Question

Consider the following program:

interface Printable {
   String getPrintable();//from  w  ww . j  av a2s.  co  m
}

class Shape implements Printable {
   public String getPrintable() {
      return "Shape ";
   }
}

class Log implements Printable {
   public String getPrintable() {
      return "Log ";
   }
}

public class Main {
   public static void overload(Shape side) {
      System.out.print(side.getPrintable());
   }

   public static void overload(Log side) {
      System.out.print(side.getPrintable());
   }

   public static void overload(Printable side) {
      System.out.print("Printable ");
   }

   public static void overload(Object side) {
      System.out.print("Object ");
   }

   public static void main(String[] args) {
      Printable firstAttempt = new Shape();
      Log secondAttempt = new Log();
      overload(firstAttempt);
      overload((Object) firstAttempt);
      overload(secondAttempt);
      overload((Printable) secondAttempt);
   }
}

What is the output of this program when executed?

  • a) Shape Shape Log Log
  • b) Printable Object Log Printable
  • c) Shape Object Log Printable
  • d) Printable Shape Log Printable


b)

Note

Overloading is based on the static type of the objects (while overriding and runtime resolution resolves to the dynamic type of the objects).

Here is how the calls to the overload() method are resolved:.

overload(firstAttempt); --> firstAttempt is of type Printable, hence it resolves to overload(Printable).
overload((Object)firstAttempt); -> firstAttempt is casted to Object, hence it resolves to overload(Object).
overload(secondAttempt); ->  secondAttempt is of type Log, hence it resolves to overload(Log).
overload((Printable)secondAttempt); -> secondAttempt is casted to Printable, hence it resolves to overload(Printable).



PreviousNext

Related