4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

No enclosing instance of type Hoge is accessible.

Posted at

概要

こんなコードを書いてみたらエラーが発生したので、メモ。

public class Hoge {
    private class Fuga(){
        public String name;
    }
    public static void main(String[] args) {
        Fuga fuga = new Fuga();
    }
}
No enclosing instance of type Hoge is accessible. 
Must qualify the allocation with an enclosing instance of type Hoge 
(e.g. x.new A() where x is an instance of Hoge).

Hoge クラスの内部にアクセスできないよエラー!

解決方法

Fuga を static クラスにする

public class Hoge {
    // static class にする
    private static class Fuga(){
        public String name;
    }
    public static void main(String[] args) {
        Fuga fuga = new Fuga();
    }
}

Hoge を生成してから Fuga を生成

public class Hoge {
    private static class Fuga(){
        public String name;
    }
    public static void main(String[] args) {
        // 一度 Hoge のインスタンスを生成してから Fuga のインスタンスを生成
        Hoge hoge = new Hoge();
        Fuga fuga = hoge.new Fuga();
        // これでもできる
        Fuga fuga2 = new Hoge().new Fuga();
    }
}
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?