Object Creation & “this” in java
Published in
1 min readOct 25, 2018
In this blog, we will take a look inside JVM object creation and “this” object reference.
Everyone knows how to create a class:
public class Rectangle {
int width;
int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getHeight() {
Rectangle rectangle = new Rectangle(4, 5);
return height;
}
public int getWidth() {
return width;
}
}
How you create an object:
Rectangle rectangle = new Rectangle(4,5);
How JVM understands the object creation:
During the compilation phase, JVM creates a method name <init> with the same parameters as your constructor. So Object creation for Rectangle class will look like this.
Rectangle rectangle = new Rectangle;
Rectangle.<init>(rectangle,4,5);
This looks strange let's expand <init>(rectangle,4,5):
So the first parameter of every instance method is always reference of its object. Internally this first parameter is referred to as “this”.
Rectangle.<init>(rectangle,4,5);
<init>(Rectangle this, int width, int height)
{
this.width = width;
this.height = height
}
JVM’s instruction set for object creation and assignment:
Rectangle rectangle = new Rectangle(4,5);
translates to
new #2 // class Rectangle
dup
iconst_4
iconst_5
invokespecial #3 // Method Rectangle."<init>":(II)V
astore_1
JVM’s instruction set for object creation:
new Rectangle(4,5);
translates to
new #2 // class Rectangle
dup
iconst_4
iconst_5
invokespecial #3 // Method Rectangle."<init>":(II)V
pop