What are the 3 different contexts a class can be declared?

Viewed 69

I am told there are three different contexts in which a class can be declared in Java.
It has to do with the location within a program, but I can't think of what they are.

Obviously a class can be declared at the top of a page, the only other example I can think of is like a nested class?
I feel I may be going about this the wrong way.

3 Answers

In a package

package com.example.mypackage;

public class TheClass {
}

In a class

package com.example.mypackage;

public class OuterClass {
    class InnerClass {
    }
}

Anonymously

public class MainClass {
    public static void main(String[] args) {
        AbstractClass myObject = new AbstractClass() {
            // overrides and other fields of the
            // anonymous class goes in this block
        };
    }
}

EDIT: As @daniu stated in the comment, a class can also be created in a method:

public class MainClass {
    public static void main(String[] args) {
        class MethodClass {
        }
        MethodClass myObject = new MethodClass();
    }
}

There are actually 4 distinct syntactic contexts:

  1. In the "compilation-unit" context; i.e. a top-level class declaration.

      package foo;
      public class Bar{}
    
  2. As a nested class declaration in a class declaration.

      package moo;
      public class Cow {
          public class Inner {}
      }
    
  3. As a nested class declaration in a method declaration.

      package too;
      public class Far {
          public void test() {
              class MethodInner{}
          }
      }
    
  4. As an anonymous class declaration in a new expression. The expression could appear in a variety of contexts. For example:

      package goo;
      public class Tar {
          public void test() {
              Runnable r = new Runnable() {
                  public run() { }
              };
          }
      }
    

This may be what you are looking for:

public class TopLevel {

    public static void main(String[] args) {
        TopLevel topLevel = new TopLevel();
        Nested nested = new TopLevel.Nested();
        Inner inner = topLevel.new Inner();
    }

    public static class Nested {
    }

    public class Inner {
    }
}
Related