When should I use “this” in a class?

后端 未结 18 2167
情书的邮戳
情书的邮戳 2020-11-21 23:36

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x i

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 23:54

    this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:

    public class circle {
        int x;
        circle(int x){
            this.x =x;
            //class variable =local variable 
        }
    } 
    

    this can also be use to call one constructor from another constructor. e.g.:

    public class circle {
        int x;
    
        circle() { 
            this(1);
        }
    
        circle(int x) {
            this.x = x; 
        }
    }
    

提交回复
热议问题