next up previous contents
Next: Interface 3: Alarm Clock Up: Java Notes Previous: Interface 1: Implementing

Interface 2: Implementing 2

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

import ITest.*;// Needs ITest package

class A implements Example
{
  // Can have a nested interface
  private interface Local{}

  // Implementation of interface variable
  public void f(int x)
  {
    System.out.println("A:f " + x);

    // Use the interface variables
    System.out.println(f);
    System.out.println(Example.f); // Also allowed
    System.out.println(m);
    System.out.println(n);
    System.out.println(p);

    // name is declared in a non public inherited
    // interface and cannot be accessed outside
    // the same package.
    // System.out.println(name); // Error
    // System.out.println(X.name);  // Error

    // interface variables are final so
    // can't do this assignment
    // m = 5; // Error

    // This member class implements a nested interface
    // declared in the interface Example.
    // Why you would want to do this is another
    // matter...
    class NestedClass implements Example.Nested
    {
      public void z()
      {
        System.out.println("NestedClass:z");
      }
    }
    NestedClass nest = new NestedClass();
    nest.z();
  }

  // Must override g and h as well
  public void g()
  {
    System.out.println("A:g ");
  }

  public int h(int x)
  {
    System.out.println("A:h " + x);
    return x * 2;
  }
}

class InterfaceTest
{
  public static void main(String[] args)
  {
    A a = new A();
    a.f(10);

    Thing t = new Thing();
    t.f(20);

    // Can't access a nested private interface
    // A.Local l; // Error
  }
}



Ananda Amatya
9/15/1999