一、this关键字1.this的类型:哪个对象调用就是哪个对象的引用类型
二、用法总结1.this.data; //访问属性
2.this.func(); //访问方法
3.this(); //调用本类中其他构造方法
三、解释用法1.this.data这种是在成员方法中使用
让我们来看看不加this会出现什么样的状况
class mydate{ public int year; public int month; public int day; public void setdate(int year, int month,int day){ year = year;//这里没有加this month = month;//这里没有加this day = day;//这里没有加this } public void printdate(){ system.out.println(year+"年 "+month+"月 "+day+"日 "); }}public class testdemo { public static void main(string[] args) { mydate mydate = new mydate(); mydate.setdate(2000,9,25); mydate.printdate(); mydate mydate1 = new mydate(); mydate1.setdate(2002,7,14); mydate1.printdate(); }}
我们想要达到的预期是分别输出2000年9月25日,2002年7月14日。
而实际输出的结果是
而当我们加上this时
class mydate{ public int year; public int month; public int day; public void setdate(int year, int month,int day){ this.year = year; this.month = month; this.day = day; } public void printdate(){ system.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 "); }}public class testdemo { public static void main(string[] args) { mydate mydate = new mydate(); mydate.setdate(2000,9,25); mydate.printdate(); mydate mydate1 = new mydate(); mydate1.setdate(2002,7,14); mydate1.printdate(); }}
就实现了赋值的功能,为了避免出现差错,我们建议尽量带上this
2.this.func()这种是指在普通成员方法中使用this调用另一个成员方法
class student{ public string name; public void doclass(){ system.out.println(name+"上课"); this.dohomework(); } public void dohomework(){ system.out.println(name+"正在写作业"); }}public class testdemo2 { public static void main(string[] args) { student student = new student(); student.name = "小明"; student.doclass(); }}
运行结果:
(3)this()
这种指在构造方法中使用this调用本类其他的构造方法
这种this的使用注意以下几点
1.this只能在构造方法中调用其他构造方法
2.this要放在第一行
3.一个构造方法中只能调用一个构造方法
运行结果
以上就是java中this方法怎么使用的详细内容。