package javaObjectOrientedProgrammingMooc;
public class Car {
private String band;
private String color;
Car(){
band = "Test";
color = "grey";
}
Car(String band, String colorIn){
band = band; // ATTENTION
color = colorIn;
}
public String getBand() {
return band;
}
public String getColor() {
return color;
}
}
In line 11, we find that band = band , the left band is a member variable which belong to class Car, the right band is local varaible which belong to function Car(String band, String colorIn).
Maybe you have reliazed that the are same, so, it's hard to distinguish, wo we use this to solve this problem. we use this refer member variable, written as this.band = band.
this have three functions:
this refer member variable in class.
this.member_variable
public Student(int sno, String sname) {
this.sno = sno;
this.sname = sname;
}
this can call constructor.
public Student(int sno) {
this.sno = sno;
}
public Student(int sno, String sname) {
this(sno);
this.sname = sname;
}
this(parameter) // Atteneion, no function name between this and ()
this调用构造方法,this 调用必须是方法的第一条语句
![](https://i-blog.csdnimg.cn/blog_migrate/a1de4fe6ef581fb047796b5ab977e1a2.png)
在构造方法中调用其他构造方法,最多只能调用一次
![](https://i-blog.csdnimg.cn/blog_migrate/1ccf3b01d501226b2a8e3de68afc2f87.png)
this调用构造方法 不能出现在非构造方法中
![](https://i-blog.csdnimg.cn/blog_migrate/2bd2d8020e46c1c93506b376f2f8972c.png)
this can refer current object.
没太弄明白这个是什么意思
Summary:this 主要在构造方法和非静态的成员方法中使用,主要是引用当前对象的成员或调用当前对象的方法。