今天在写一个小的程序时出现No enclosing instance of type Hidden is accessible. Must qualify the allocation with an enclosing instance of type Hidden (e.g. x.new A() where x is an instance of Hidden).的错误,寻找了很长时间,终于解决了。
我的程序是:
public class Hidden {
class Father{
/*public void str(){
//System.out.println("输出父类的str!");
}*/
String str="父类的STR成员";
}
class Son extends Father{
/*public void str(){
System.out.println("输出子类的str!");
}*/
String str="子类的STR成员";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Father father=new Father();
Son son=new Son();
System.out.println("输出父类的方法:");
System.out.println(father.str);
System.out.println("输出子类的方法:");
System.out.println(son.str);
}
}
运行时提示:No enclosing instance of type Hidden is accessible. Must qualify the allocation with an enclosing instance of type Hidden (e.g. x.new A() where x is an instance of Hidden).
着了修改了好几次,但是还是解决不了。最后在网上找了一篇文章,解决了。
Father和Son类都是内部类,只有静态类才能被实例化。所以将Father和Son类前面添加static就可以了。
或者:
public class Hidden {
class Father{
/*public void str(){
//System.out.println("输出父类的str!");
}*/
String str="父类的STR成员";
}
class Son extends Father{
/*public void str(){
System.out.println("输出子类的str!");
}*/
String str="子类的STR成员";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Hidden hidden=new Hidden();
Father father=hidden.new Father();
Son son=hidden.new Son();
System.out.println("输出父类的方法:");
System.out.println(father.str);
System.out.println("输出子类的方法:");
System.out.println(son.str);
}
}
原文链接:http://www.tuicool.com/articles/RFrANzr