next up previous contents
Next: Inner and Nested Classes: Up: Java Notes Previous: Inner and Nested Classes:

Inner and Nested Classes: Member 3

/**
 *  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 A{
  public class B{
    public class C{
      public void test(){
        System.out.println(name);
        System.out.println(B.this.name);
        System.out.println(A.this.name);
      }

      private String name = "C";
    }

    public void test(){
      System.out.println(name);
      System.out.println(A.this.name);

      C c = new C();
      c.test();

      // Can do this as method already has 
	  // member object reference to an A
      B b = new B();
      // b.test();//Watch out infinite recursion!!
    }

    private String name = "B";
  }

  public void test(){
    System.out.println(name);
    B b = new B();
    b.test();

    // Can't do this (no B object specified)
    // B.C c = new C(); // Error

    // Can do this
    B.C c = b.new C();
    c.test();
  }

  private String name = "A";
}

class l1Memb3{//Class7
  public static void main(String[] args){
    A a = new A();

    // Cannot create a member class object 
	// without an A object
    // A.B = new B(); // Error

    // Can do this. 
	// Note the form of the new expression
    A.B b = a.new B();
    b.test();

    // Can also do this to create 
	// a C object using a B object
    A.B.C c = b.new C();
    c.test();

    // Cannot do this 
	// as a C object needs a B object
    // A.B.C c1 = a.new C(); // Error
  }
}
/******** sample compilation & run *******
# javac l1Memb3.java 
# java l1Memb3
B
A
C
B
A
C
B
A
# 
******************************************/



Ananda Amatya
9/15/1999