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

后端 未结 2 1156
轻奢々
轻奢々 2021-01-19 14:27

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.

相关标签:
2条回答
  • 2021-01-19 15:06

    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.

    0 讨论(0)
  • 2021-01-19 15:06
    non-static variable this cannot be referenced from a static context"
    

    this error indicate that you are accessing the variable which is not static without its object. to access the non static variable you need the object of that type. only static variables can be accessed without any object.

    the solution is same as @dasblinkenlight provided.

    0 讨论(0)
提交回复
热议问题