instanceof

With inheritance, we can do something like this (assuming Person and Student were as defined earlier in the chapter):

Person p = null;
if (condition) 
{
    p = new Person("Bob", 24);
}
else 
{
    p = new Student("Bob", 24, "ECE", 3.2);
}

Here, we either store a Person object OR a Student object in p, depending on some condition. It might be nice to have a way to tell which type of object we’ve stored. We can do this with the instanceof command. Here’s how:

if (p instanceof Student) 
{
    //if we want, convert to a Student variable
    Student s = (Student) p;
}

This condition will evaluate to true if we stored a Student object inside p. We may then want to cast p to a Student variable, as we did above.