代码:
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 类,可能会相互影响而导致编译出错