我的java学习-this指代的是什么

在初学习java的时候,对于this.x 和x的关系老是搞不清楚

  public class Point implements Moveable{
        private int x ;
        private int y ;
        public Point( int x , int y ){
        this.x = x ;
        this.y = y ;
    }

这个private int x ; private int y ;里面的x,y是class Point里面的类变量,私有性质的,不能直接被外部类调用,需要通过类Point里面提供的setX(),setY(),getX(), getY()这些方法来访问。

this.x,this.y

使用了this来指代,this其实就是当前所在类class Point,this.x指的就是private int x,class Point里面的类变量,在class类内部方法里面使用当前类变量,就是用this.x指代的方法用来和传递进来的参数做区分。

pulic Point(int x, int y){}带有2个参数,在pulic Point这个构造函数里面或者在其他的类方法里面,参数(int x, int y)在自己类方法内部比如setX(int x)就是直接使用,this.x = x; 前面的this.x不能把他们分开看,这是一个整体,表示的是class Point类内部的类变量,后面的x是类方法所传递进来的变量。

猜你喜欢

转载自blog.csdn.net/qq_43399072/article/details/83045198