How does the this
pointer points to the object itself? Is it a java implementation or is it a compiler implementation?
Definition and Usage. The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
There are 6 ways where this keyword can be used in Java. They are as follows: Used with a field. Used to invoke a constructor.
Integration modules can be implemented to use Java class files. Using a Java class file eliminates the need for integration component registration and configuration. Additionally, all the underlying integration module implementations are transparent to the process management product.
In the JVM bytecode, local variable 0 (basically register 0) points to the current object when a method is invoked. The compiler simply uses this
as an alias for local variable 0.
So I guess the answer is that the compiler implements this
.
Sounds like a philosophical question. I am not sure that a Java implementation is.
this
is defined in the JLS and is a keyword in Java and the compile has to comply with that standard. When you have a method like
object.method(args)
what is actually called in byte code is a method which looks like
method(object, args);
where this
is the first argument.
At the JVM level, the parameters don't have names and the JIT could optimise the argument away if its not actually used.
Well if you are interested why not look at the byte code generated by the compiler
class HelloWorld
{
private String hello = "Hello world!";
private void printHello(){
System.out.println (this.hello);
}
public static void main (String args[]){
HelloWorld hello = new HelloWorld();
hello.printHello();
}
}
Compile using
%JAVA_HOME%/bin/javac HelloWorld.java
Get bytecode using
javap -c HelloWorld
edit add output
enter code here
HelloWorld();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()
4: aload_0
5: ldc #2; //String Hello world!
7: putfield #3; //Field hello:Ljava/lang/String;
10: return
public static void main(java.lang.String[]);
Code:
0: new #6; //class HelloWorld
3: dup
4: invokespecial #7; //Method "<init>":()V
7: astore_1
8: aload_1
9: invokespecial #8; //Method printHello:()V
12: return
}
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