概要
こんなコードを書いてみたらエラーが発生したので、メモ。
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();
}
}