Non-static variable that cannot be referenced from a static context when instantiating a class

I get the error "non-static variable that cannot be referenced from static context" when I try to add a new instance of the Edge class (subclass?) To my administrator. I cannot figure out what I am 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;
        }
    }
}

      

+3


source to share


2 answers


You need to make a Edge

nested class static

:

public static class Edge {
    ...
}

      



Otherwise, the nested class remains non-static, which means that it retains a reference to an 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.

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

it has nothing to do with the external interface Map

.

+9


source


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

      

this error indicates that you are accessing a variable that is not static without an object. you need an object of that type to access a non-static variable. they can only be accessed by static variables without any object.



the solution is the same as @dasblinkenlight.

0


source







All Articles