105

An enclosing instance that contains is required

Below is the code. positionObj is the object that I am trying to use and it is giving me the above error.

It's unclear why.

package toolBox;
import toolBox.Secretary.positionObj;    

public class PositionManagement {
    public static HashMap<String, Secretary.positionObj> main(String vArg){
        positionObj newPosition=new positionObj();
    }
}
askewchan
  • 45,161
  • 17
  • 118
  • 134
jason m
  • 6,519
  • 20
  • 69
  • 122

3 Answers3

143

You're trying to use the non-static inner positionObj class without an instance of Secretary for it to belong to.
A non-static inner class must belong to an instance of its parent class

You should probably change positionObj to a normal class or a static inner class.

Alternatively, you can write someSecretary.new positionObj() to create an instance of the inner class that belongs to the someSecretary instance.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • agreed, but this general statement is a bit unclear. could you provide an example or point me somewhere that might better explain this? thanks – jason m Nov 28 '10 at 17:07
  • yes. i realized when trying to debug that if I made my positionObj to static that it worked (in its Secretary class). I am happy and all that it now works, but thanks for the pointer. Will look into actual cause of this error. – jason m Nov 28 '10 at 17:13
  • 2
    The actual cause of the error is that you didn't give a parent instance. Do not use non-static inner classes unless you really need one _and you understand how they work_. http://c2.com/ppr/wiki/JavaIdioms/NoPublicInnerClasses.html – SLaks Nov 28 '10 at 17:14
  • both solutions work perfectly [1- making the positionObj class static and 2- using OuterClass.new classObj() ]. thanks – jason m Nov 28 '10 at 17:23
  • Yes. However, you need to understand your code base well enough to figure out which one is correct. – SLaks Nov 28 '10 at 17:26
26

First create an object of Outer class. In this case I think "Secretary". Then create positionObj. Like this,

Secretary x = new Secretary();
Secretary.positionObj y = x.new positionObj();
Teshan
  • 361
  • 3
  • 3
0

The correct generic signature would be

public static HashMap<String, positionObj> main(String vArg)

you dont need to qualify positionObj since you already import it.

However, I am pretty sure a main method must conform to the signature below. If you intend to have main be the main method for your program, change the signature to

 public static void main(String[] args) {...}

you can create a separate static method that returns a Map and invoke it from main.

As a note, all classes should begin with a capital letter, positionObj, should be PositionObj.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236