“this” keyword: Working mechanism in Java

前端 未结 5 1082
执笔经年
执笔经年 2020-12-29 09:49

After learning Java for sometime, its the first time the use of this keyword has confused me so much.

Here is how I got confused. I wrote the following

5条回答
  •  萌比男神i
    2020-12-29 10:26

    1. Why x and this.x point to the x of base class and not the Child class?

    we can see this example:

    class TestBase {
        private int x;
        public void a() {
            this.x++;
        }
        public int getX() {
            return x;
        }
    }
    public class Test extends TestBase{
        private int x;
        public int getX() {
            return this.x;
        }
    }
    

    and generated bytecode:

    public class Test extends TestBase{
    public Test();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method TestBase."":()V
       4:   return
    
    public int getX();
      Code:
       0:   aload_0
       1:   getfield        #2; //Field x:I
       4:   ireturn
    
    public void a();
      Code:
       0:   aload_0
       1:   invokespecial   #3; //Method TestBase.a:()V
       4:   return
    
    }
    

    In there the Test extends TestBase and the method a is compiled into the Test class, it will call it's father 1: invokespecial #3; //Method TestBase.a:()V.

    the Test's getX method will call 1: getfield #2; //Field x:I from it's own constant pool table, http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings

    the TestBase class bytecode:

    class TestBase extends java.lang.Object{
    TestBase();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."":()V
       4:   return
    
    public void a();
      Code:
       0:   aload_0
       1:   dup
       2:   getfield        #2; //Field x:I
       5:   iconst_1
       6:   iadd
       7:   putfield        #2; //Field x:I
       10:  return
    
    public int getX();
      Code:
       0:   aload_0
       1:   getfield        #2; //Field x:I
       4:   ireturn
    
    }
    

    the method a() also will get x from it's own constant pool by getfield #2; //Field x:I.

    so there is another thing: the Java's getter and setter is evil.

提交回复
热议问题