Java OCA OCP Practice Question 193

Question

Given:

3. interface Runnable { }
4. interface Testable { }
5. class Task implements Runnable { }
6. class Job extends Task implements Testable { }
7. public class Tree {
8.   public static void main(String[] args) {
9.     String s = "0";
10.     Task b = new Task();
11.     Task b2 = new Job();
12.     Job s2 = new Job();
13.     if((b instanceof Runnable) && (b2 instanceof Testable))  s += "1";
14.     if((s2 instanceof Runnable) && (s2 instanceof Testable)) s += "2";
15.     System.out.println(s);/*from w  w w.  j  a va 2 s. co m*/
16.   }
17. }

What is the result?

  • A. 0
  • B. 01
  • C. 02
  • D. 012
  • E. Compilation fails
  • F. An exception is thrown at runtime


D is correct.

Note

instanceof can look up through multiple levels of an inheritance tree.

instanceof is commonly used before attempting a downcast.

after line 15, it would be possible to say Job s3 = (Job)b2;.




PreviousNext

Related