开发者

Is there a limit on the number of local inner classes inside a method?

I'm having a bit of difficulty with some java code

class foo{
   public bar() {
      class innerA {}
      class innerB {} // Only this one is valid beca开发者_如何学Pythonuse it was declare last
   }
}

My Problem: Only the last declared inner class (innerB) is visible within foo::bar(). Additionally, I cannot reference either inner class from within the other. Example:

innerB{
    private innerA _a; // Error
}

My Question: Is there some limit on the number of local inner classes you can have within a method? Can local inner classes instantiate other local inner class object? Should they?

EDIT: I miss-typed in my IDE and had some scoping issues... thanks again!

TIA, noob


Please post the code you really try to make work, and the error message you get from the Java compiler. The code you posted isn't valid Java. Everything you want to do is doable. Here's a working example :

public class Foo {
    public void bar() {
        class InnerA {
            public void hello() {
                System.out.println("Hello from InnerA");
            }
            public String getName() {
                return "InnerA";
            }
        }

        class InnerB {
            private InnerA aInB = new InnerA();
            public void hello() {
                System.out.println("Hello from InnerB");
                System.out.println("In InnerB, got name of InnerA : " + aInB.getName());
            }
        }

        InnerA a = new InnerA();
        InnerB b = new InnerB();

        a.hello();
        b.hello();
    }

    public static void main(String[] args) {
        new Foo().bar();
    }
}

Running it gives :

Hello from InnerA
Hello from InnerB
In InnerB, got name of InnerA : InnerA


You neglected to specify a return type for bar().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜