非静态变量在创建类的实例时,不能从静态上下文引用它

当我尝试将Edge类的新实例(子类?)添加到我的arraylist时,我得到“无法从静态上下文引用的非静态变量”错误。 我无法弄清楚我做错了什么!

public class stuff{ public static void main(String[] args){ ArrayList edges = new ArrayList(); edges.add(new Edge(1,2, 3, 4) ); } public class Edge{ private int x1; private int y1; private int x2; private int y2; private double distance; private boolean marked; //constructors public Edge(int point1_x, int point1_y, int point2_x, int point2_y){ x1 = point1_x; y1 = point1_y; x2 = point2_x; y2 = point2_y; int x_dist = x1 - x2; int y_dist = y1 - y2; distance = Math.hypot((double)x_dist, (double)y_dist); marked = false; } //methods public void mark(){ marked = true; } public boolean isMarked(){ return marked; } public double weight(){ return distance; } } } 

您需要使Edge嵌套类static

 public static class Edge { ... } 

否则,嵌套类保持非静态,这意味着它保留对其外部类的实例的引用。 因此,只有实例方法或您可以访问外部类实例的其他位置才能实例化内部类。

通常,公共静态类是顶级类的良好候选者。 例外情况是,当它们与外部类相关联时,它们在其上下文之外没有任何意义。 例如, Map.Entry在其外部Map接口之外没有任何意义。

 non-static variable this cannot be referenced from a static context" 

此错误表示您正在访问没有其对象的非静态变量。 要访问非静态变量,您需要该类型的对象。 只能在没有任何对象的情况下访问静态变量。

解决方案与提供的@dasblinkenlight相同。