0

In the below code what exactly is the function of instanceof operator? I understand that if block executes only if its true i.e (obj instanceof MountainBike==true).Assuming its true why does we should again typecast (MountainBike)obj?

    if (obj instanceof MountainBike) {
      MountainBike myBike = (MountainBike)obj;
     }
  • It says "If the object *can* be seen as a MountainBike, get a view of it as MountainBike". – RealSkeptic Nov 24 '16 at 09:35
  • I assume obj is of type "Object" which is the parent of all objects. If you don't cast you will not be able to use functions from MountainBike class ie the child. – user1211 Nov 24 '16 at 09:36

1 Answers1

0

Because the compiler does not know, at compile time, that this object is a "MountainBike", so a cast is needed

DZDomi
  • 1,685
  • 15
  • 13