Java OCA OCP Practice Question 1933

Question

Given three classes MyClass1, MyClass2, and MyClass3,

where MyClass2 is a subclass of MyClass1, and MyClass3 is a subclass of MyClass2,

which one of these boolean expressions is true only when an object denoted by reference o has actually been instantiated from class MyClass2, as opposed to from MyClass1 or MyClass3?.

Select the one correct answer.

  • (a) (o instanceof MyClass2) && (!(o instanceof MyClass1))
  • (b) (o instanceof MyClass2) && (!(o instanceof MyClass3))
  • (c) !((o instanceof MyClass1) || (o instanceof MyClass2))
  • (d) (o instanceof MyClass2)
  • (e) (o instanceof MyClass2) && !((o instanceof MyClass1) || (o instanceof MyClass3))


(b)

Note

The expression (o instanceof MyClass2) will return true if the object referred to by o is of type MyClass2 or a subtype of MyClass2.

The expression (!(o instanceof MyClass3)) will return true unless the object referred to by o is of type MyClass3 or a subtype of MyClass3.

Thus, the expression (o instanceof MyClass2) && (!(o instanceof MyClass3)) will only return true if the object is of type MyClass2 or a subtype of MyClass2 that is not MyClass3 or a subtype of MyClass3.

Given objects of the classes MyClass1, MyClass2, and MyClass3, this expression will only return true for objects of class MyClass2.




PreviousNext

Related