非静态变量,在创建类的实例时不能从静态上下文中引用 [英] non-static variable this cannot be referenced from a static context when creating instance of class

查看:69
本文介绍了非静态变量,在创建类的实例时不能从静态上下文中引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将Edge类(子类?)的新实例添加到我的arraylist时,出现无法从静态上下文引用的非静态变量"错误.我不知道我在做什么错!

I'm Getting the "non-static variable this cannot be referenced from a static context" error when I try to add a new instance of the Edge class(subclass?) to my arraylist. I can't figure out what I'm doing wrong!

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 {
    ...
}

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

Otherwise, the nested class remains non-static, which means that it retains a reference to the instance of its outer class. As a consequence, only instance methods or other places where you have access to an instance of the outer class can instantiate the inner class.

通常,公共静态类是顶级类的理想候选者.唯一的例外是,当他们将其外部类与外部类联系在一起时,他们在上下文之外毫无意义.例如, Map.Entry 在其外部 Map 界面之外毫无意义.

In general, public static classes are good candidates for top-level classes. The exception is when they are tied to their outer class to the extend that they make no sense outside its context. For example, Map.Entry makes no sense outside its outer Map interface.

这篇关于非静态变量,在创建类的实例时不能从静态上下文中引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆