40

I am developing a small desktop application in Netbeans. This is my first program and I am facing a very strange type of error. I know I did some thing wrong but unable to trace what I am doing wrong :(

Please help me in resolving this error.

Description: I have a default package Src and I am creating new Java classes in this package as required. Along with other classes I made a class X like this:

public class X
{
    public class Y
    {//some member functions and variables exist here}

    public class Z
    {//some member functions and variables exist here}

    //some member functions and variables exist here
}

Now I need to create instance of one of the inner classes in some other class that exists in the same package, like this:

public X.Y oY = new X.Y();

but I am getting the following error:

an enclosing instance that contains X.Y is required

Please help me in resolving this error.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
Jame
  • 21,150
  • 37
  • 80
  • 107
  • possible duplicate of [An enclosing instance that contains is required](http://stackoverflow.com/questions/4297857/an-enclosing-instance-that-contains-my-reference-is-required) – Joshua Taylor Sep 26 '13 at 12:41

3 Answers3

85

First of all you have to create an object of X class (outer class) and then use objX.new InnerClass() syntax to create an object of Y class.

Try,

X x=new X();
X.Y y=x.new Y();
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 8
    Wow! I leaned something today! Strange syntax. Very nice! +1 – Martijn Courteaux Oct 01 '11 at 10:18
  • 2
    Does anyone know why they made the language this way? What purpose does this serve? – wonton Mar 31 '13 at 07:59
  • Sorry for the late response here, I believe it's to be able to support both static nested classes and non-static nested classes. I'm not an expert, but from what I am reading, I believe this is to force subordinate classes to be members of an instance of a the parent (non-static) and create a different syntax for subordinate classes that don't require a parent (static). https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html – joelc Dec 14 '17 at 16:07
36

You want to declare static inner classes: public static class Y.

Hugh
  • 8,872
  • 2
  • 37
  • 42
  • 2
    Because the OP didn't mention it needs to stay non-static. If he needs the enclosing instance, he'll comment about the compiler error from making it a static and learn even more from his question. – Philipp Reichart Oct 01 '11 at 10:19
  • 2
    +1 for this answer - the accepted answer isn't entirely complete as it assumes the class is required from a non-static context. In my case, this was not true. – devrobf May 10 '13 at 17:28
10

Declare Y as static to avoid creating instance of X.

public class X
{
    public static class Y {
    }
}
Jon_Li
  • 101
  • 1
  • 2