Java 出现 No enclosing instance of type Test1 is accessible.(转,自己也遇到了!)

最近在看Java,在编译写书上一个例子时,由于书上的代码只有一部分,于是就自己补了一个内部类。结果编译时出现:No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing instance of type E(e.g.  x.new A() where x is an instance of E). E指代我写的那个内部类。

根据提示,没有可访问的内部类E的实例,必须分配一个合适的内部类E的实例(如x.new A(),x必须是E的实例。)看着这句提示,我就纳闷了,我已经用new实例化了这个类,为什么还不行呢。

于是百度谷歌了一下相关资料。原来我写的内部类是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。所以不做其他变动的情况下最简单的解决办法是将public class改为public static class.

 

另外一种解决方法:把这些类分开写,也就是把这几个class 放在不同的文件中,也可解决问题

 

summarize:

      类中的静态方法不能直接调用动态方法。

 

 

 

 

 

技术分享
  1  
  2 
  3 package index01;
  4 
  5  
  6 
  7 public class Test1 {
  8 
  9  
 10 
 11  
 12 
 13 public static void main(String[] args){
 14 
 15  
 16 
 17 System.out.println("1");
 18 
 19 Person p1 = new Person("Andy","beijing","uic");
 20 
 21 System.out.println(p1.info());
 22 
 23  
 24 
 25  
 26 
 27 System.out.println("2");
 28 
 29 Teacher t1 = new Teacher("andy", "zhuhai ","uic ","student ");
 30 
 31 System.out.println(t1.info());
 32 
 33     }
 34 
 35  
 36 
 37  public static class Person {
 38 
 39 private String name;
 40 
 41 private String school;
 42 
 43 private String location;
 44 
 45  
 46 
 47 Person(String name, String school){
 48 
 49 this.name=name;
 50 
 51 this.school=school;
 52 
 53 }
 54 
 55 Person(String name, String location, String school){
 56 
 57 this.name=name;
 58 
 59 this.location=location;
 60 
 61 this.school= school;
 62 
 63 }
 64 
 65 public String info(){
 66 
 67 return "name: "+ name+"\nlocation: "+ location +"\nschool: "+school;
 68 
 69 }
 70 
 71 }
 72 
 73  public static class Teacher extends Person{
 74 
 75 private String position;
 76 
 77  
 78 
 79  
 80 
 81 Teacher(String name, String school){
 82 
 83 super(name, school);
 84 
 85  
 86 
 87 }
 88 
 89 Teacher(String name, String location, String school){
 90 
 91 super(name, location, school);
 92 
 93  
 94 
 95 }
 96 
 97 Teacher(String name, String location, String school, String position){
 98 
 99 super(name, location, school);
100 
101 this.position=position;
102 
103 } 
104 
105 public String info(){
106 
107 return super.info()+"\nposition: "+ position;
108 
109 }
110 
111   }
112 
113  }
114 
115  
testcal

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。