In the main method of a program. I tried to initialize an inner class but it didn't work. Why does this happen?

So this doesn't compiles:

Code:

public class ExampleError {

public static void main (String[] args) {

InnerClass innerClass = new InnerClass();

}

class InnerClass {

}

}

But the following does:

Code:

public class ExampleError {

public static void main (String[] args) {

InnerClass innerClass = new InnerClass();

}

}

class InnerClass {

}

Any help please?

02-12-2011, 06:54 AM

pbrockway2

Note that in the second example InnerClass is not actually an inner class.

The thing about inner classes (unlike, say, static nested classes) is that they have an enclosing instance.

For example suppose I have a class Sequence within which is an inner class Itr (which might implement Iterator). Then Itr has to be an iterator of something ie Itr has to be associated with an instance of Sequence. The associated Sequence instance can be thought of as the context of Itr.

When, in the first example, you say "InnerClass innerClass = new InnerClass();" the compiler will object because there is no instance of ExampleError of which this InnerClass type is to be associated. In the second example, despite its name InnerClass is just an ordinary type and you can call new InnerClass() any time you like - including within a static method like main().

02-12-2011, 07:05 AM

Humbly

Thanks for the explanation. :)

Can you please give me example code of how innerClass could be associated to ExampleError?

02-12-2011, 07:16 AM

pbrockway2

The following compiles without error:

Code:

public class ExampleError {

void someMethod() {
// innerClass will be associated with the instance
// whose someMethod() was called
InnerClass innerClass = new InnerClass();
}

I trust you know what you're doing as it's not my intention to give you enough syntacic rope for you to hang yourself on a whacky design. This is the New to Java forum - the shallow end, if you like - and it's not advisable to attempt triple back somersaults here...

02-12-2011, 07:17 AM

toadaly

Here's why it's invalid:

Code:

public class ExampleError {

int memberVariable;

public static void main (String[] args) {

InnerClass innerClass = new InnerClass();

}

class InnerClass {

InnerClass() {
memberVariable++;
}

}

}

As you can see, an inner class has access to the parent class' members. It's really just a sub-namespace of the parent class. However, you can make a static inner class, and then it would be available to static methods.

Code:

public class NoLongerAnError {

public static void main (String[] args) {

InnerClass innerClass = new InnerClass();

}

static class InnerClass {

}

}

02-12-2011, 07:33 AM

pbrockway2

It's a nitpick but, just to keep the terminology straight, such static nested classes are not properly referred to as inner.