Java class 定義於不同位置的差異

package classes.one;

public class A {

    class E {
        // public protected private
    }

    static class F {

    }

    public void method() {
        class G {

        }
    }
}

//public class B {
//  The public type B must be defined in its own file
//}

class C {

}

//private class D {
//  Illegal modifier
//}

class 可定義於

  1. file 中
  2. class 中
  3. method 中

in File

同一個 file 中可以有多個 class,但只能有一個是 public
因此只有同 package 能使用
同 package 也不能再有同名的 class

in Class

可以有 public、protected、private、default 存取修飾

A a = new A();
//E e = new E(); // No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new A() where x is an instance of A).
E e = a.new E(); // 必須由實例創建
F f = new F(); // 靜態類別才可由類別創建

in Method

只能在方法內部使用,即使在 class 也無法使用
class in class 沒有先後順序的差別,但 class in method 的定義一定要寫在前面

public void method() {
//  G g = new G(); // 還沒定義不能使用
    class G {

    }
    G g = new G();  
}