6

Here's my simple class:

public class Project {
    private int size;
    private Obj tree;
    static Obj insert( Obj t, String s ) { // t is null
        t = new Obj();
        t.val = s;
        return t;
    }
    public Project()
    {
      Obj tree = new Obj();
      int size=0;
    }
    public class Obj
    {
      public String val;
      public Obj()
      {
        val=null;
      }
    }     
}

However, when I try to create a new object in the insert() function, I get this error:

Error: non-static variable this cannot be referenced from a static context

1 Answer 1

6

Your Obj class is not static == it's an inner class. This means that it needs an instance of the enclosing class Project to live.

From the static method insert, there is no such Project instance, hence the compiler error.

The Obj class doesn't seem to need any instance variables in Project, so there is no reason to keep it non-static. Make the Obj class static in Project.

public static class Obj
Sign up to request clarification or add additional context in comments.

1 Comment

Aha, thank you a lot. I'll mark your answer when I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.