代碼:
public class hello {
public static void main(String[] args) {
Person ming = new Person();
Person hong = new Person();
ming.setName("Xiao Ming");
// TODO: 給Person增加重載方法setName(String, String):
hong.setName("Xiao Hong");
System.out.println(ming.getName());
System.out.println(hong.getName());
}
// here comes the quesion!
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
報錯:
No enclosing instance of type Main
is accessible. Must qualify the allocation with an enclosing instance of type Main
(e.g. x.new A() where x is an instance of Main).
沒有可訪問的Main類型的封閉實例。 必須使用Main類型的封閉實例來限定分配(例如x.new A(),其中x是Main的實例)。
解決:
只要把Person類放在hello 類外面即可
FAQ:
- 同一個src下 不同的.java文件可能定義相同的Person 類,可能會相互影響而導致編譯出錯