Outer outer = new Outer();
an Object
of Outer
class is created on heap and reference variable points to it.
If I understand it right when I write
Outer.Inner inner=outer.new Inner();
an object of Inner
class is created on heap and inner
points to it. In heap we have two separate objects which contains their own instance variables.
But if I write
Outer.Inner inner=new Outer().new Inner();
still two Object
would be created on heap one for Outer
and other for Inner
. But with reference the inner
only Inner
Object's
members are accessible . Who is referring to the outer Object
on heap? If it is not referred by any reference then it should be eligible for garbage collection which would then impact the usage of inner
.
An object gets memory on the heap. In stack memory, the variable of class type stores the address of an object. In heap memory, a physical copy of an object is stored and the reference or address of this copy in the variable of the associated class.
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.
The object values are stored in heap memory.
In C# there are two places where an object can be stored -- the heap and the stack. Objects allocated on the stack are available only inside of a stack frame (execution of a method), while objects allocated on the heap can be accessed from anywhere.
An inner class contains a hidden reference to its outer class instance. That hidden reference keeps the outer class instance alive if there are no other references to it.
To see this in action, take this source code and compile it:
public class Outer {
public class Inner {
}
}
Now use the java class inspection tool javap
to see the hidden reference:
$ javap -p Outer\$Inner
Compiled from "Outer.java"
public class Outer$Inner {
final Outer this$0;
public Outer$Inner(Outer);
}
You'll see that there is a package-scope hidden reference called this$0
of type Outer
- this is the reference that I talked about above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With