Home Segments Top Top Previous Next

200: Mainline

Instance methods can have ordinary arguments, in addition to the target instance. You might, for example, have an instance method named scaledRating that multiplies the rating of its target instance by a scale factor supplied as an ordinary argument:

*-- Target instance 
| 
|                *-- Ordinary argument 
|                | 
v                v 
m.scaledRating(0.75) 

The definition of a scaledRating instance method is similar to that of a rating instance method. The only difference is the addition of an ordinary parameter, scaleFactor:

public class Movie { 
 // First, define instance variables: 
 public int script, acting, direction; 
 // Define rating: 
 public int rating (double scaleFactor) { 
  return (int) (scaleFactor * (script + acting + direction)); 
 } 
} 

The following shows the new version in action:

public class Demonstrate { 
 // Define main: 
 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(0.75)); 
 } 
} 
--- Result --- 
The rating of the movie is 17