Muneeb Nasir
Muneeb Nasir

Reputation: 2504

static inner class treated as static member or normal class?

As we know, static members has shared memory, they have no concern with object:

class TestStatic {
    public static int a = 10;
}

class Main{
    public static void main(//){
        TestStatic obj1 = new TestObj//;
        obj1.a=15;
        TestStatic obj2 = new TestObj//;
        // obj2.a equals 15 too
    }
}

Suppose we have following scenario:

class TestStatic {

    public static class InnerClass {
    }

    public static void main(//) {
         TestStatic.InnerClass classobj1 = new TestStatic.InnerClass();
         TestStatic.InnerClass classobj2 = new TestStatic.InnerClass();
    }

}

How Java treats classobj1 and classobj2? Allocates two different memory locations or a shared one? If different memory locations, what is the reason?

Upvotes: 1

Views: 69

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074058

how java treats classobj1 and classobj2? allocate two different memory location or shared one?

Two separate ones. Exactly as though you had:

Map m1 = new HashMap();
Map m2 = new HashMap();

if different memory location, what is the reason?

Because the static here relates to the class, not to instances of the class. If you have a nested class that isn't static, it's related to instances of the containing class.

The Oracle Nested Class Tutorial may be useful.

Upvotes: 3

Related Questions