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;这个语句,而在只有一个类的源文件中会提示错误???求解啊!!!!!!!!!!!!!!!!!
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;这个语句,而在只有一个类的源文件中会提示错误???求解啊!!!!!!!!!!!!!!!!!
类中的成员变量是有默认值的,对于int,默认为0,所以可以执行sum += 1;
在只有一个类的源文件中,只要是类的成员变量,应该也是没问题的,我想楼主可能是要说在一个方法中会提示错误吧!方法中的变量是要初始化的。
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换个位置就可以了...什么原因捏??第二个问题还是不太明白..
这句语句会默认初始化 sum=0.