next up previous
Next: 1.11.2 Casts and Static Up: 1.11 Loose Ends Previous: 1.11 Loose Ends

  
1.11.1 Local variables

Method parameters in Java play exactly the same role as function parameters in Scheme. They are local variables bound to the corresponding argument values. They are destroyed when the method returns.1.3 Java also provides a mechanism, akin to Scheme's local construct, for introducing local variables to perform a subcomputation without invoking a help method. In Java, local variable definitions can be inserted as statements in any statement sequence (such as a function body or compound statement). Each such variable is accessible only in program text between its definition and the end of the statement sequence.

For example, it is convenient in writing a main method to test a class to introduce local variables to hold test data values. The following main for the class DeptDirectory relies on this technique.

  public static void main(){
    Entry cork = new Entry("Corky","DH 3104","x 6042");
    Entry matthias = new Entry("Matthias","DH 3106","x 5732");
    Entry ian = new Entry("Ian","DH 3102","x 3843");
    DeptDirectory dd = new Cons(ian, new Cons(cork, 
      new Cons(matthias, Empty.only)));

    System.out.println("ian " + dd.findAddress("ian") + " " + 
      dd.findPhone("ian"));
    System.out.println("cork " + dd.findAddress("cork") + " " + 
      dd.findPhone("cork"));
    System.out.println("matthias " + dd.findAddress("matthias")
      + " " + dd.findPhone("matthias"));
  }

Java imposes an important restriction on the use of local variables in anonymous classes. Any local variable mentioned in an anonymous class definition must be declared final. In practice, this is not a significant restriction. In fact, most attempted uses of non-final local variables in inner classes correspond to errors in program logic. In any case where you need to mention a non-final local variable in an inner class, you can simply introduce an extra final variable with the required value. Ironically, this transformation often converts a logically incorrect program in to a correct one! We will revisit this issue in later in the monograph in connection with programming graphical user interfaces.


next up previous
Next: 1.11.2 Casts and Static Up: 1.11 Loose Ends Previous: 1.11 Loose Ends
Corky Cartwright
2000-01-07