java中的this

this是一个关键字,全部小写。

一个对象一个this。

this是一个变量,是一个引用,this保存当前对象的内存地址,指向自身。  可以说this代表的就是‘当前对象’

this存储在堆内存当中对象的内部。

this只能使用在实例方法中。谁调用这个实例方法,this就是谁。

public class ThisTest{
    public static void main(String[] args){
        Custom c1 = new Custom("AB");
        c1.shopping();
    }
    
}
class Custom{
    String name;
    public Custom(){}
    public Custom(String n){
        name = n;
    }
    public void shopping(){
        System.out.println(this.name+"shopping");
    }
}

静态方法无this,因为this代表的是当前对象,而静态方法的调用不需要对象。或者说 this代表当前对象,而静态方法中不存在当前对象。。。。

 

总结:严格区分实例变量,静态变量,局部变量。

 

this的使用进阶:

  在开发过程中,为了增加代码的可读性,以及代码中的变量的可读性,可以使用this.no = no ; 其中的this表示当前对象的,区分实例变量和局部变量。。。

  且在区分局部变量和实例变量的时候是不能省略的。

this的新语法:

  this可以通过当前的构造方法去调用另一个本类的构造方法,可以使用以下格式:(this的作用就是解决代码复用的问题)

public Date(){
  this(1997, 10, 31);  注意,对this的调用必须是构造器中的第一个语句。
}
public Date(int year, int mouth, int day){
 this.year = year;
 this.mouth = mouth;
 this.day = day;
}

 

posted @ 2022-06-21 12:12  _八级大狂风  阅读(535)  评论(0编辑  收藏  举报