只要在类的方法中访问类中的属性,那么属性前一定要追加“this”关键字的形式
从this的实际使用来讲可以做三件事
1.调用本类属性
pubic void people{
String name;
int age;
// 构造方法
public people(String name,int age){
this.name = name;
this.age = age;
}
// 得到信息
public String getInfo(){
return "myName:"+this.name+"MyAge:"+this.age;
}
}
public class Demo01 {
public static void main(String[] args) throws Exception {
People people=new People("小明", 10);
System.out.println(people.getInfo());
}
2.调用本类方法(基本、构造)
pubic void people{
String name;
int age;
// 构造方法
public people(String name,int age){
this.name = name;
this.age = age;
}
pulic String toString(String name,int age){
return name+":"+age;
}
// 得到信息
public String getInfo(){
return this.toString();
}
}
public class Demo02 {
public static void main(String[] args) throws Exception {
People people=new People("小明", 10);
System.out.println(people.getInfo());
}
3.表示当前对象(相对概念)
class People {
public void print() {
//哪个对象调用了print()方法,this就自动与此对象指向同一块内存地址
System.out.println("this=" + this);//this 就是当前调用对象
}
}
public class Demo03 {
public static void main(String[] args) throws Exception {
People people= new People ();
People people2= new People ();
System.out.println("people=" + people);
people.print();
System.out.println("people2=" + people2);
people2.print();
}
}