What is the meaning of “this” in Java?

后端 未结 21 2616
走了就别回头了
走了就别回头了 2020-11-21 05:41

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if i

21条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:13

    Instance variables are common to every object that you creating. say, there is two instance variables

    class ExpThisKeyWord{
    int x;
    int y;
    
    public void setMyInstanceValues(int a, int b) {
        x= a;
        y=b;
    
        System.out.println("x is ="+x);
        System.out.println("y is ="+y);
    }
    
    }
    
    
    
    
    class Demo{
    public static void main(String[] args){
    
    ExpThisKeyWord obj1 = new ExpThisKeyWord();
    ExpThisKeyWord obj2 = new ExpThisKeyWord();
    ExpThisKeyWord obj3 = new ExpThisKeyWord();
    
    obj1.setMyInstanceValues(1, 2);
    obj2.setMyInstanceValues(11, 22);
    obj3.setMyInstanceValues(111, 222);
    
    
    
    }
    }
    

    if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method. How do you think JVM correctly assign the values for every object? there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;

    public void setMyInstanceValues(int a, int b) {
        this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
        this.y=b;
    
        System.out.println("x is ="+x);
        System.out.println("y is ="+y);
    }
    

提交回复
热议问题