Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

what's the purpose of instanceof keyword.

807607Dec 20 2006 — edited Dec 21 2006
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 18 2007
Added on Dec 20 2006
19 comments
453 views