当我尝试将Edge类的新实例(子类?)添加到我的arraylist时,我得到"无法从静态上下文引用的非静态变量"错误.我无法弄清楚我做错了什么!
public class stuff{
public static void main(String[] args){
ArrayList<Edge> edges = new ArrayList<Edge>();
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
das*_*ght 10
您需要创建Edge嵌套类static:
public static class Edge {
...
}
Run Code Online (Sandbox Code Playgroud)
否则,嵌套类保持非静态,这意味着它保留对其外部类的实例的引用.因此,只有实例方法或您可以访问外部类实例的其他位置才能实例化内部类.
通常,公共静态类是顶级类的良好候选者.例外情况是当它们与外部类相关联时,它们在其上下文之外没有任何意义.例如,Map.Entry在其外部Map接口之外没有任何意义.
| 归档时间: |
|
| 查看次数: |
2224 次 |
| 最近记录: |