0
0

More than 1 year has passed since last update.

static class

Last updated at Posted at 2023-01-08

static field, static method

inner class(non static)の中のstatic field/methodはコンパイルエラーになる

static field, static methodはinstanceに依存しないという意味なので
instance依存のclassであるnon-static classの中に入れられないからである。
(形だけenclosing-classの中に入っていて、呼び出しの際にenclosing-classを
経由して呼び出すというだけの内包関係で、instanceとして中に入っているわけではない。)
static field/methodはstatic classの中に入れられる。
もし、static field/method, non-static field/methodをまとめてclass内の別classにする場合も、static classとする。
non-static field/methodだけの場合、non-static class(inner class)に入れる。
static classは厳密にはinner classとは呼ばない。

public class Outer {
    static int i;
    class Inner {
        static int j;    //compile error
    }
    public static void main(String[] args) {
    }
}
com/mycompany/mavenproject1/Outer.java:[21,20] 内部クラスcom.mycompany.mavenproject1.Outer.Innerの静的宣言が不正です
  修飾子'static'は定数および変数の宣言でのみ使用できます

inner class of staticにしてエラー解消

public class Outer {
    static int i;
    static class Inner {
        static int j;
    }
    public static void main(String[] args) {
    }
}

static classとすることで、new Outer().new Inner()ではなく
new Inner()でインスタンス化できる。

public class Outer {
    static int i;
    static class Inner {
        int j;
        void method(){
            System.out.println("i  am method");
        }
    }
    public static void main(String[] args) {
        Inner i = new Inner();
        i.j = 0;
        i.method();
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0