World's most popular travel blog for travel bloggers.

InstanceOf Keyword in java

, , No Comments
InstanceOf Keyword 
In the previous chapter we have learnt about the IS-A relationship between subclass and superclass. In this chapter we will be learning the programatic implementation of IS-A relationship.

Example : IS-A Relationship Verification

class FourWheeler extends Vehicle{}
class TwoWheeler extends Vehicle{}
class WagonR extends FourWheeler{}

public class Vehicle 
    public static void main( String[] args )
     FourWheeler v1 = new FourWheeler();
     TwoWheeler v2 = new TwoWheeler();
     WagonR v3 = new WagonR();
        System.out.println(v1 instanceof Vehicle);
        System.out.println(v2 instanceof Vehicle);
        System.out.println(v3 instanceof Vehicle);
        System.out.println(v3 instanceof FourWheeler);

Output :


InstanceOf Operator :

In the above example we have used this following statement –
System.out.println(v1 instanceof Vehicle);
the instanceof operator is used to check whether TwoWheeler is actually a Vehicle, and FourWheelet is actually a Vehicle.

Invalid Use of InstanceOf Operator :

System.out.println(v3 instanceof TwoWheeler);


Post a Comment

Let us know your responses and feedback