Occasionally, you need to work with predicates that work on class
instances, rather than on numbers. For example, if you want to determine
whether a particular instance is an instance of a particular class, you use
the instanceof
operator, which returns true
if the
instance is either a direct instance of the given class or a direct
instance of a subclass of that class.
Suppose, for example, that the JamesBondMovie
class extends the
Movie
class, which extends the Attraction
class. Then, a
James Bond movie is an instance of all three classes. An ordinary movie is
an instance of the Movie
class as well as of the Attraction
class, but it is not an instance of the JamesBondMovie
class:
public class Demonstrate { public static void main (String argv[]) { JamesBondMovie jbm = new JamesBondMovie(); Movie m = new Movie(1, 1, 1); System.out.println(jbm instanceof Attraction); System.out.println(jbm instanceof Movie); System.out.println(jbm instanceof JamesBondMovie); System.out.println(m instanceof Attraction); System.out.println(m instanceof Movie); System.out.println(m instanceof JamesBondMovie); } } --- Result --- true true true true true false