繁体   English   中英

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

[英]non-static variable this cannot be referenced from a static context when creating instance of class

当我尝试将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;
        }
    }
}

您需要使Edge嵌套类static

public static class Edge {
    ...
}

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM