Java OCA OCP Practice Question 1007

Question

Given the following class definitions, the expression

(obj instanceof A) &&  !  (obj instanceof C) &&  !  (obj instanceof D)  

correctly identifies whether the object referred to by obj

was created by instantiating class B rather than classes A, C and D?

class A  {} 
class B extends A  {} 
class C extends B  {} 
class D extends C  {} 

Select 1 option

  • A. True
  • B. False


Correct Option is  : B

Note

The given expression will not be able to distinguish between an object of class A and an object of class B.

It will return true in both the cases.

Also, The last part !(obj instanceof D) of the given expression is redundant because anything which is not instance of C cannot be an instanceof D either !

Correct expression would be (obj instanceof B) && ! (obj instanceof C).

This will return true only if obj points to an object of class B and not of A, C, or D.




PreviousNext

Related