To decide which rating
instance method to use on, say, a
Movie
instance, the Java compiler searches up from the
Movie
class, through the subclasssuperclass chain, to find the
first instance method named rating
. For the Movie
instance
example, the only rating
instance method that the Java compiler
finds is the one in the Movie
class.
On the other hand, the rating
instance method selected by the Java
compiler to work on JamesBondMovie
instances is the one in the
JamesBondMovie
class, and the rating
instance method in the
Movie
class is said to be shadowed or
overridden
by that lower-level instance method.
Thus, you see the following result when your program calls the rating
method.
For both the ordinary movie and the James Bond movie, the constructor in
the Movie
class assigns 5
to the script
,
acting
, and direction
instance variables.
public class Demonstrate { public static void main (String argv[]) { Movie m = new Movie(); System.out.println("The movie rating is " + m.rating()); JamesBondMovie jbm = new JamesBondMovie(); System.out.println("The James Bond movie rating is " + jbm.rating()); } } --- Result --- Calling zero-parameter Attraction constructor Calling zero-parameter Movie constructor The movie rating is 15 Calling zero-parameter Attraction constructor Calling zero-parameter Movie constructor The James Bond movie rating is 20