Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How inner class object resides in memory?

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.

like image 579
Pankaj Avatar asked Jun 18 '15 02:06

Pankaj


People also ask

How are class objects stored in memory?

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.

How objects are stored in memory in Java?

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.

Where in memory are objects stored?

The object values are stored in heap memory.

How objects are stored in memory in C#?

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.


1 Answers

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.

like image 89
Erwin Bolwidt Avatar answered Oct 16 '22 17:10

Erwin Bolwidt