Java基础【01】this用法

来源:互联网 发布:选择框选中each数组 编辑:程序博客网 时间:2024/06/05 07:13

指代对象

this用于指代调用成员方法的当前对象

public class ThisDemo {      int number;    ThisDemo increment(){         number++;         return this;    }      private void print(){         System.out.println("number="+number);    }    public static void main(String[] args) {        ThisDemo tt=new ThisDemo();         tt.increment().increment().increment().print();    }}

访问本类的成员变量和成员方法

public class ThisDemo {      String name="Mick";    public void pt(){        System.out.println("成员方法");    }    public void print(String name){        this.pt(); //指代成员方法        System.out.println("类中的属性 name="+this.name); //指代成员属性        System.out.println("局部传参的属性="+name);    }       public static void main(String[] args) {        ThisDemo tt=new ThisDemo();        tt.print("Orson");    }}

调用本类重载的构造方法

this引用用在重载的构造方法中,调用本类已经定义的构造方法

public class MyDate{    public MyDate(int year,int month,int day){        this.year=year;        this.month=month;        this.day=day;    }    public MyDate(MyDate d){        this(d.year,d.month,d.day); //指代本类已经声明的构造方法    }}

注意点

在构造函数中,this()必须是第一行,只能使用一次,不能使用this调用当前的构造方法

原创粉丝点击