next up previous contents
Next: Classes: Constructors Up: Java Notes Previous: Classes: Member Variables

Classes: Declaration Example

/**
 *  This code is from the book:
 *  Winder, R and Roberts, G (1998)
 *  Developing Java Software
 *  John Wiley & Sons.
 *  It is copyright (c) 1997 Russel Winder
 *  and Graham Roberts.
 */

class ClassScope{

  //A private variable with the class scope
  private int n = 1;

  //Access ClassScope object private variable
  //in a ClassScope method.
  public void alter(final ClassScope c){
    //private variable n of
    //ClassScope type parameter c accessed
    c.n = 123;
  }

  //Access an instance object private variable n
  public String toString(){
    return new Integer(n).toString();
  }
}

// Test the ClassScope varaible.
public class l1ClDecl1{//ScopeTest
  public static void main(String[] args){
    // Create ClassScope objects using public method
    ClassScope a = new ClassScope();
    ClassScope b = new ClassScope();
    // Access private variables of one object 
    // using a public method of another object
    a.alter(b);
    System.out.println("Object a: " + a);
    System.out.println("Object b: " + b);
    // No direct access to private object variables:
    // a.n = 123;
  }
}
/******** sample compilation & run ********
# javac l1ClDecl1.java
# java l1ClDecl1
Object a: 1
Object b: 123
# 
******************************************/



Ananda Amatya
9/15/1999