Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only create a object of a nest inner class inside a member function

Suppose I have an inner class B that I will create an instance of inside one of the member functions of outer class, is there a way that I can do it without creating a instance of outer class?

Thanks a lot.

class A {
    class B {

    }

    public void function() {
       // create an instance of B, normally have to create a 
       // instance of A to be bond to by b
       B b = new B();
    }
}
like image 933
user1935724 Avatar asked Jan 31 '26 04:01

user1935724


1 Answers

The only way you do this is by declaring B static:

class A {
    static class B {

This means that B does not have an instance of A associated with it, and can be instantiated in contexts where no outer instance of available.

That said, your current code compiles fine as-is (since function() is non-static, there is an instance of A available in this context).

like image 120
NPE Avatar answered Feb 01 '26 17:02

NPE