0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

static classとは(Java備忘録)

0
Posted at

Javaでは以下のようにクラスをネストする。

class Outer {
    class Inner {
    }
}

メリット

  • Outer専用classを作成する(privateも追加することでOuter内部からしか読めないクラスとなる)
  • Outer.Innerのように名前空間を統一して可読性を高める
  • Outer側privateメンバにInner内からアクセス可能
  • etc ...

このとき、InnerインスタンスはOuterインスタンスがなければ生成できない。
例として、ネストされたのInnerインスタンスが欲しいとき、以下のようになる。

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

ただし、ネストされたクラスにstaticを追加したときはOuterインスタンスが必須ではなくなる。
クラス宣言↓

public class Outer {
    static class Inner {
    }
}

Innerインスタンス生成↓

Outer.Inner inner = new Outer.Inner();

Outerとの結びつきという意味合いは薄れるが(privateとしない限り)、パッケージ内での名前衝突を避けたいがネストされたクラスは自由に使いたいという需要にこたえる。

ただし、Outerオブジェクトへの直接的な繋がりがなくなるので、staticでないOuterの変数への暗黙の参照は行えなくなる。

class Outer {
    private int x = 10;

    static class Inner {
        void f() {
            // System.out.println(x); // コンパイルエラー
        }
    }
}

staticであれば、特定のオブジェクトへ属さず、Outerクラスに属するため可能

class Outer {
    private static int a = 10;
    
    static class Inner {
        void f() {
            System.out.println(a);       // OK
        }
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?