奇怪的问题:non-static variable this cannot be referenced from a static context
求助,将两个class放在主类里就汇报错,如题目里所写。//code1
import java.util.*;
//将Apple()和Orange()放在AppleTest1里就会报错:静态上下文利不应该将非静态变量作为引用
public class AppleTest1 {
class Apple {
private static long counter;
private final long id = counter++;
public long id(){ return id; }
}
class Orange {}
public static void main(String [] args) {
ArrayList apples = new ArrayList();
for( int i = 0; i < 3; i++ )
apples.add(new Apple());
apples.add(new Orange());
}
}
//code2
import java.util.*;
//将Apple()和Orange()放在AppleTest1外则正常
class Apple {
private static long counter;
private final long id = counter++;
public long id(){ return id; }
}
class Orange {}
public class AppleTest1 {
public static void main(String [] args) {
ArrayList apples = new ArrayList();
for( int i = 0; i < 3; i++ )
apples.add(new Apple());
apples.add(new Orange());
}
}
请问是什么原因造成的?
--------------------编程问答--------------------
--------------------编程问答--------------------
文件名AppleTest1.java,这样放着没问题
class Apple {
private static long counter;
private final long id = counter++;
public long id() {
return id;
}
}
class Orange {
}
public class AppleTest1 {
public static void main(String[] args) {
ArrayList apples = new ArrayList();
for (int i = 0; i < 3; i++) {
apples.add(new Apple());
apples.add(new Orange());
}
}
}
我知道这样没问题呀,我问的是为什么将Apple和Orange放在AppleTest1里就有问题了。 --------------------编程问答-------------------- 普通的内部类不能有static数据 --------------------编程问答-------------------- The field counter cannot be declared static; static fields can only be declared in static or top level types --------------------编程问答-------------------- 给你修改的代码如下,你使用的内部类,内部类如果不是静态的,就不能有静态成员变量。稍微在改了一些main方法中的代码,你没用泛型
import java.util.ArrayList;
public class AppleTest1
{
class Apple
{
private long counter; //删掉static
private final long id = counter++;
public long id()
{
return id;
}
}
class Orange
{
}
public static void main(String[] args)
{
ArrayList<Apple> apples = new ArrayList<Apple>();
ArrayList<Orange> orange = new ArrayList<Orange>();
for (int i = 0; i < 3; i++)
apples.add(new AppleTest1().new Apple());
orange.add(new AppleTest1().new Orange());
}
}
补充:Java , Java SE