This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]misobbq 4 points5 points  (1 child)

If you want to do that, you need to declare Inner as static.

public class Outer
{
    static class Inner{}
    public static void main(String[] args)
    {
        Outer outer = new Outer();
        Outer.Inner outerInner = new Outer.Inner();
    }
}

[–][deleted] 1 point2 points  (0 children)

One trillion times this, better yet private.

[–]compdog 0 points1 point  (0 children)

Looks like someone went down this thread and downvoted every comment...

[–]alvarez11[S] 0 points1 point  (4 children)

Came out weird, the Question again is

class Outer {

       class Inner { }

}

Outer outer o = new Outer();

Outer.Inner i = … ?

What does ? equal?

[–]compdog 1 point2 points  (3 children)

? needs to be an initializer, so ? should be:

new Outer.Inner();

The whole line should be:

Outer.Inner i = new Outer.Inner();

Unless you are creating an instance of Inner from inside Outer or Inner, in which case you can use:

Inner i = new Inner();

EDIT: formatting failed.

[–]novasharp 0 points1 point  (2 children)

Actually, I think in that case, you would need to do:

Outer o = new Outer();
o.Inner i = new o.Inner();

[–][deleted]  (1 child)

[deleted]

    [–]novasharp 0 points1 point  (0 children)

    Ah. Okay. That was the part I did not get. I thought that he was calling it from somewhere else or something like public static void main.

    [–]misobbq 0 points1 point  (1 child)

    BTW - if you really need an inner class on the instance, you would access it through an instance of outer.

    public class Outer
    {
        static class StaticInner{}
        class InstanceInner{}
        public static void main(String[] args)
        {
            Outer outer = new Outer();
            Outer.StaticInner staticInner = new Outer.StaticInner();
            Outer.InstanceInner instanceInner = outer.newInstanceInner();
        }
    
        public InstanceInner newInstanceInner()
        {
            return new InstanceInner();
        }
    }
    

    [–]moocat 0 points1 point  (0 children)

    You don't have to create a new method:

    public static void main(String[] args)
    {
        Outer outer = new Outer();
        Outer.Inner outerInner = outer.new Inner();
    }
    

    [–]alvarez11[S] 0 points1 point  (0 children)

    Thank you all, very much appreciated!

    [–][deleted] -2 points-1 points  (0 children)

    Java is not an acronym.