11.this
this:看上去,是用于区分局部变量和成员变量同名的情况。
this为什么可以解决这个问题?
this代表什么?
this:
this代表本类的对象。
this代表它所在函数所属对象的引用。
简单说,哪个对象在调用this所在的函数,this就代表哪个对象。
this的应用:
当定义类中功能时,该函数内部要用到调用该函数的对象时,这时用this来表示这个对象。
this语句:
用于构造函数之间互相调用
只能定义在构造函数的第一行
public class This_06 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Employee e1=new Employee("lisi");
Employee e2=new Employee("zhangsan");
e1.speak();
e2.speak();*/
/*Employee e1=new Employee(20);
Employee e2=new Employee(25);
e1.compare(e2);*/
Employee e1=new Employee("lisi",30);
}
}
class Employee{
private String name;
private int age;
Employee(int age) {
this.age=age;
}
Employee(String name){
this.name=name;
}
Employee(String name,int age){
//this.name=name; //替换为this(name),构造函数之间的相互调用
this(name);
this.age=age;
}
public void speak(){
System.out.println("name="+this.name+",age="+this.age);
this.show();
}
public void show(){
System.out.println(this.name);
}
//需求:定义一个用于比较年龄是否相同的功能,比较是否同龄人
public boolean compare(Employee e){
if(this.age==e.age){
return true;
}
return false;
}
}