Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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;
        }
    }
}
like image 947
thrown Avatar asked Dec 26 '22 09:12

thrown


1 Answers

You need to make the Edge nested class 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.

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.

like image 168
Sergey Kalinichenko Avatar answered Dec 28 '22 22:12

Sergey Kalinichenko