How is the 'this' variable in Java actually set to the current object?

前端 未结 5 1926
囚心锁ツ
囚心锁ツ 2021-02-03 21:19

Consider:

class TestParent{
  public int i = 100;
  public void printName(){
    System.err.println(this); //{TestChild@428} according to the Debugger.
    Syste         


        
5条回答
  •  孤城傲影
    2021-02-03 22:05

    In essence, there is no difference between

    this.foo()
    

    and

    anyObject.foo()
    

    as both are "implemented" the same way. Keep in mind that "in the end" "object orientation is only an abstraction, and in "reality" what happens is something like:

    foo(callingObject)
    

    In other words: whenever you use some object reference to call a method ... in the end there isn't a call on some object. Because deep down in assembler and machine code, something like "a call on something" doesn't exist.

    What really happens is a call to a function; and the first (implicit/invisible on the source code level) parameter is that object.

    BTW: you can actually write that down in Java like:

    class Bar {
       void foo(Bar this) { ... }
    

    and later use

    new Bar().foo();
    

    And for this.fieldA, in the end: you have a reference to some location in memory; and a table that tells you on which "offset" you will find fieldA.

    Edit - just for the record. If you are interested in more details about foo(Bar this) - you can turn to this question; giving the details in the Java spec behind it!

提交回复
热议问题