1.this是什么?
this是一个引用类型,保存了内存地址,在堆中的每个java对象都有this,
this保存了内存地址指向自身。
2.this能用在哪些地方?
(1)this可以用在成员方法中
this用在成员方法中,谁去调用这个成员方法,this就代表谁。
this指的就是当前对象。(this. 可以省略)
this可以用来区分成员变量和局部变量
(2)this可以用在构造方法中
语法:this(实参)
通过一个构造方法去调用另外一个构造方法
目的:代码重用
牢记:this(实参)必须出现的构造方法的第一行
(其他地方是不能用this的)
(3)this不能用在静态方法中(所谓静态方法指的是含staatic的方法,例如public static void m1() )
原因:静态方法的执行不需要java对象的存在,直接使用 类名. 的方式访问,
而this代表当前对象,所以静态方法中根本就没有this
3.this:
1.使用在类中,可以用来修饰属性、方法、构造器
2.表示当前对象或者是当前正在创建的对象
3.当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来表明该变量时类成员
4.在任意方法内,如果使用当前类的成员变量或成员方法可以在其前面添加this,增强程序的阅读性
5.在构造器中使用“this(形参列表)”显式的调用本类中重载的其它的构造器>5.1 要求“this(形参列表)”要声明在构造器的首行!
>5.2 类中若存在n个构造器,那么最多有n-1构造器中使用了this。
public class TestPerson {
//程序入口public static void main(String[] args) {
Person p1 = new Person(); //创建Person对象
System.out.println(p1.getName() + ":" + p1.getAge());
Person p2 = new Person("BB",23);
int temp = p2.compare(p1);
System.out.println(temp);
}
}
class Person{
private String name;
private int age;
//Constructor构造方法
public Person(){
this.name = "AA"; //无参构造方
this.age = 1;
}
public Person(String name){
this();
this.name = name;
}
public Person(String name,int age){
this(name);
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void eat(){
System.out.println("eating");
}
public void sleep(){
System.out.println("sleeping");
this.eat();
}
//比较当前对象与形参的对象的age谁大。
public int compare(Person p){
if(this.age > p.age)
return 1;
else if(this.age < p.age)
return -1;
else
return 0;
}
}