Java OCA OCP Practice Question 1931

Question

Which letters will be printed when the following program is run?.


class MyClass {}//from   w  w w  .j a  v a  2 s .c om
class MyClass2 extends MyClass {}
class MyClass3 extends MyClass2 {}
class MyClass4 extends MyClass3 {}

// Filename: Main.java
public class Main {
  public static void main(String[] args) {
    MyClass2 b = new MyClass3();
    MyClass a = b;
    if (a instanceof MyClass) System.out.println("MyClass");
    if (a instanceof MyClass2) System.out.println("MyClass2");
    if (a instanceof MyClass3) System.out.println("MyClass3");
    if (a instanceof MyClass4) System.out.println("MyClass4");
  }
}

Select the three correct answers.

  • (a) MyClass will be printed.
  • (b) MyClass2 will be printed.
  • (c) MyClass3 will be printed.
  • (d) MyClass4 will be printed.


(a), (b), and (c)

Note

The program will print MyClass, MyClass2, and MyClass3 when run.

The object denoted by the reference a is of type MyClass3.

The object is also an instance of MyClass and MyClass2, since MyClass3 is a subclass of MyClass2 and MyClass2 is a subclass of MyClass.

The object is not an instance of MyClass4.




PreviousNext

Related