Nested Types

Classes that are declared outside of any class are top-level classes. Nested classes are classes declared as members of other classes or scopes.

There are four kinds of nested classes:

  • static member classes,
  • nonstatic member classes,
  • anonymous classes
  • local classes.

Static Member Classes

A static member class is a static member of an enclosing class. A static member class cannot access the enclosing class's instance fields and invoke its instance methods.

It can access the enclosing class's static fields and invoke its static methods including private fields and methods.

The following code has a static member class declaration.


class Demo {
  public static void main(String[] args) {
    Main.EnclosedClass.accessEnclosingClass(); 
    Main.EnclosedClass ec = new Main.EnclosedClass();
    ec.accessEnclosingClass2(); 
  }
}

class Main {
  private static int outerVariable;

  private static void privateStaticOuterMethod() {
    System.out.println(outerVariable);
  }

  static void staticOuterMethod() {
    EnclosedClass.accessEnclosingClass();
  }

  static class EnclosedClass {
    static void accessEnclosingClass() {
      outerVariable = 1;
      privateStaticOuterMethod();
    }

    void accessEnclosingClass2() {
      staticOuterMethod();
    }
  }
}

static member classes can declare multiple implementations of their enclosing class.

 
abstract class Rectangle {
  abstract double getX();

  abstract double getY();

  abstract double getWidth();

  abstract double getHeight();

  static class Double extends Rectangle {
    private double x, y, width, height;

    Double(double x, double y, double width, double height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
    }

    double getX() {
      return x;
    }

    double getY() {
      return y;
    }

    double getWidth() {
      return width;
    }

    double getHeight() {
      return height;
    }
  }

  static class Float extends Rectangle {
    private float x, y, width, height;

    Float(float x, float y, float width, float height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
    }

    double getX() {
      return x;
    }

    double getY() {
      return y;
    }

    double getWidth() {
      return width;
    }

    double getHeight() {
      return height;
    }
  }

  private Rectangle() {
  }

  boolean contains(double x, double y) {
    return (x >= getX() && x < getX() + getWidth()) && (y >= getY() && y < getY() + getHeight());
  }
}

public class Main {
  public static void main(String[] args) {
    Rectangle r = new Rectangle.Double(10.0, 10.0, 20.0, 30.0);
    r = new Rectangle.Float(10.0f, 10.0f, 20.0f, 30.0f);
  }
}
  
Home 
  Java Book 
    Class  

Nested Classes:
  1. Nested Types
  2. Nonstatic Member Classes
  3. Anonymous Classes
  4. Local Classes