Home Segments Top Top Previous Next

194: Mainline

In instance methods, all references to instance variables refer to the particular instance variables that belong to the target instance.

Thus, you define rating as an instance method as follows:

public class Movie { 
 public int script, acting, direction; 
 public int rating () { 
  return script + acting + direction; 
 } 
} 

When this rating instance method is called on a particular Movie target, the script, acting, and direction variables that appear in the definition of rating automatically refer to the script, acting, and direction instance variables that are associated with that target:

public class Demonstrate { 
 public static void main (String argv[]) { 
  Movie m = new Movie(); 
  m.script = 8; m.acting = 9; m.direction = 6; 
  System.out.println("The rating of the movie is " + m.rating()); 
 } 
} 
--- Result --- 
The rating of the movie is 23