2

我认为这很简单,因为我很确定我以前做过,但我似乎无法让它发挥作用。我的课是:

public class City
{
    String start = null;
    String end = null;
    int weight = 0;
}

我正在做:

City cityGraph[] = new City[l];

例如,当我尝试访问 cityGraph[x].start 时,我得到一个空指针异常,所以我想我还需要初始化数组中的每个元素,所以我这样做:

for(int j = 0; j < l; j++)
        {
            cityGraph[j] = new City();
        }

但它给了我这个错误:

No enclosing instance of type Graphs is accessible. 
Must qualify the allocation with an enclosing instance 
of type Graphs (e.g. x.new A() where x is an instance of Graphs).

我不知道这意味着什么,或者如何解决它。任何帮助,将不胜感激!

4

3 回答 3

5

当您声明为这样的内部类时,可能会发生这种public class City情况public class Graphs

public class Graphs {

    public class City {
    
    }

}

这样,City如果不先构造Graphs实例,就无法构造。

您需要构建City如下:

cityGraph[j] = new Graphs().new City();
// or
cityGraph[j] = existingGraphsInstance.new City();

老实说,这没有任何意义。而是将其提取City到一个独立的类中,

public class Graphs {

}
public class City {

}

或通过声明它使其成为静态嵌套类static

public class Graphs {

    public static class City {
    
    }

}

无论哪种方式,您都可以City通过 just构建一个新的new City()

也可以看看:

于 2012-07-18T14:42:55.370 回答
1

看来您的类不是静态内部类,这意味着它需要外部类的实例才能被实例化。

有关静态与内部类的更多信息 http://mindprod.com/jgloss/innerclasses.html

于 2012-07-18T14:42:19.640 回答
0

我实际上有自己问题的答案。使类静态修复它。我不知道为什么直到我发布后我才想到这个......希望这对将来的某人有所帮助。

于 2012-07-18T14:40:01.640 回答