instanceof operator in java tells whether a particular object is an instance of a particular class.
Then why the following code is not compiling:-
public class TestCondition
{
public static void main(String[] args)
{
Pizza pizza = new Pizza("First Pizza");
String name = pizza.getName();
System.out.println("pizza instanceof Pizza : " + (pizza instanceof Pizza)); // first
System.out.println("\"First Pizza\" instanceof Pizza : " + ("First Pizza" instanceof Pizza)); // second
System.out.println("name instanceof Pizza : " + (name instanceof Pizza)); //third
}
}
class Pizza
{
String name;
public Pizza(String name)
{
this.name = name;
System.out.println("Pizza instantiated: " + name);
}
public String getName()
{
System.out.println("Pizza Name is: " + name);
return name;
}
}
it is saying incompatible types in second and third SOPs.
Shouldn't it have compiled and printed false in second and third SOPs when run.
Is it important that the object being tested must be in inheritance hierarchy of the class being tested.
When should one expect to get true/false,
and when should one expect incompatible type error.
Please help me out of this dilemma!
Thanks in advance for your replies.