Program to demonstrate how to use instanceof operator for testing IS-A relationship in Java
package com.hubberspot.code;
// Create a Shape class
interface Shape { }
// Create a Triangle class which
// implements Shape class
class Triangle implements Shape{ }
// Create a Parallelogram class which
// implements Shape class
class Parallelogram implements Shape { }
// Create a Rectangle class which
// extends Parallelogram class
class Rectangle extends Parallelogram { }
// Create a class Car in different hierarchy
class Car { }
public class InstanceOfTest {
public static void main(String[] args) {
// Create an Object of Car, Rectangle,
// Parallelogram and Triangle
Car car = new Car();
Rectangle rectangle = new Rectangle();
Parallelogram parallelogram = new Parallelogram();
Triangle triangle = new Triangle();
// Lets now have a IS-A test of all these object
// in order to know that whether a particular object
// created above is of particular type we have a
// test of it using instanceof operator / keyword
// This operator tells us whether a particular
// object is a instance of particular type or not.
// The usage : object instanceof Class
if(rectangle instanceof Shape) {
System.out.println("rectangle is a Shape");
}else{
System.out.println("rectangle is not a Shape");
}
if(triangle instanceof Shape) {
System.out.println("triangle is a Shape");
}else {
System.out.println("triangle is not a Shape");
}
if(parallelogram instanceof Shape) {
System.out.println("parallelogram is a Shape");
}else {
System.out.println("parallelogram is not a Shape");
}
if(rectangle instanceof Parallelogram) {
System.out.println("rectangle is a Parallelogram");
}else {
System.out.println("rectangle is not a Parallelogram");
}
if(car instanceof Shape) {
System.out.println("car is a Shape");
}else {
System.out.println("car is not a Shape");
}
// throws compile time error as "Incompatible conditional
// operand types Car and Rectangle" : means we are comparing
// class of different hierarchies plus they are incompatible
// types
/*if(car instanceof Rectangle) {
System.out.println("car is a Rectangle");
}else {
System.out.println("car is not a Rectangle");
} */
}
}
Output of the program :
