Er Priyatam
Er Priyatam

Reputation: 13

Gives me an error while creating an object in java

I faced an error while creating my object using a defined class in Java. Here is my code:

public class encapsulation {

    class Emp
    {
        int empId;
        String empName;
    }

    public static void main(String[]args)   
    {
        Emp e1 = new Emp();
    }
}

But it gives me an error:

No enclosing instance of type encapsulation is accessible. Must qualify the allocation with an enclosing instance of type encapsulation (e.g. x.new A() where x is an instance of encapsulation).

Here is a screeshot: Error in object creation using java

Upvotes: 0

Views: 165

Answers (2)

khelwood
khelwood

Reputation: 59112

When you have an inner class Emp in encapsulation, any instance of Emp belongs to an instance of encapsulation. If you don't want that, make it a nested class instead, by adding a static modifier:

public class encapsulation {
    static class Emp {
    ......

Now that Emp is declared static, it does not belong to any particular instance of encapsulation, so you don't need to instantiate encapsulation to instantiate Emp.

Upvotes: 2

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

You are trying to instantiate an object of an inner class. Inner class instances always need to be associated with an outer class instance. Try this -

public static void main(String[]args)
{
    encapsulation en = new encapsulation();
    encapsulation.Emp e1 = en.new Emp();
}

Check out the official tutorial for more info.

Upvotes: 2

Related Questions