public class Test6 {
public static void main(String[] args) {
Test7 t = new Test7();
t.getDay();
} class Test7 {
public int sum; public void getDay() {
for (int i = 0; i < 5; i++) {
sum += 1;
}
System.out.println(sum);
}
}
}
这样子写为什么会编译错误?Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
No enclosing instance of type Test6 is accessible. Must qualify the allocation with an enclosing instance of type Test6 (e.g. x.new A() where x is an instance of Test6). at Test6.main(Test6.java:3)还有,为什么在class Test7中sum没有初始化,但是可以执行sum+=1;这个语句,而在只有一个类的源文件中会提示错误???求解啊!!!!!!!!!!!!!!!!!

解决方案 »

  1.   

    在这里,楼主把Test7写成了Test6的内部类,而main方法是static的、但是Test不是static的,所以报错。楼主可以把Test7前加static修饰,或者把Test7写到Test6的外面。
    类中的成员变量是有默认值的,对于int,默认为0,所以可以执行sum += 1;
    在只有一个类的源文件中,只要是类的成员变量,应该也是没问题的,我想楼主可能是要说在一个方法中会提示错误吧!方法中的变量是要初始化的。
      

  2.   

    Test7 t = new (new Test6()).Test7();
      

  3.   

    class Test7 {
    public int sum; public void getDay() {
    for (int i = 0; i < 5; i++) {
    sum += 1;
    }
    System.out.println(sum);
    }
    }public class Test6 {
    public static void main(String[] args) {
    Test7 t = new Test7();
    t.getDay();
    }
    }Test6和Test7换个位置就可以了...什么原因捏??第二个问题还是不太明白..
      

  4.   

    "public int sum;"
    这句语句会默认初始化 sum=0.
      

  5.   

    放在方法体内的变量叫局部变量,如果声明时没赋值,系统是不会给它赋初值的,此时你如果直接使用了,就会报错,放在类中,而不是在方法中的变量称为成员变量,成员变量如果声明时没赋值,系统会按其类型为其分配初始值,int类型的为0,String类型的为null,double类型的为0.0等,此时直接使用是按初始值来使用的!
      

  6.   

    其实这个大括号的问题改了以后就没问题了,只是提示你sum没有赋初始值被默认为0
      

  7.   

    类的成员变量(属性)会有默认初始值,系统会自动初始化,int类型为0,引用类型为null;局部变量(方法体内)如果没有设置初始值,运行期间会报错