this的概念
Java虚拟机会给每个对象分配 this,代表当前对象。
public class test {
public static void main(String[]args){
Person p=new Person("jack",18);
p.info();
}
}
class Person{
String name;
int age;
public Person(String name,int age){ // 构造器的name,age是局部变量,而不是属性
this.name=name; // 表示当前对象的属性
this.age=age;
}
public void info(){
System.out.println(name+"\t"+age+"\t");
}
}
哪个对象调用,this就代表哪个对象。
public class test {
public static void main(String[]args){
Person p=new Person("jack",18);
p.info();
System.out.println("p的哈希值="+p.hashCode());
}
}
class Person{
String name;
int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void info(){
System.out.println("this代表的对象对应的哈希值="+this.hashCode());
}
}
使用细节
- this关键字可以用来访问本类的属性、方法、构造器。
- this用于区分当前类的属性和局部变量
- 访问成员方法:this.方法名(参数列表)
- 访问构造器语法:this(参数列表),只能在构造器中使用(只能在构造器中访问另一个构造器,提示访问构造器语法必须放在第一条语句)
- this不能在类定义的外部使用,只能在类定义的方法中使用
public class test {
public static void main(String[]args){
Person p=new Person();
Person p2=new Person();
p.f2();
p.f3();
}
}
class Person{
String Str="test.java";
public Person(){
this("tom",3); // 必须在第一行
System.out.println("这是Person的构造器");
}
public Person(String name,int age){
System.out.println("这是Person(String name,int age)");
}
public void f1(){
System.out.println("f1方法");
}
public void f2(){
System.out.println("f2方法");
f1();
this.f1();
}
public void f3(){
System.out.println("Str="+Str);
}
}
使用示例
public class test {
public static void main(String[] args){
Person p=new Person("jack",18);
Person q=new Person("rick",66);
System.out.println("q与p的比较结果="+p.compareTo(q));
}
}
class Person{
String name;
int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public boolean compareTo(Person p){
return this.name.equals(p.name)&&this.age==p.age;
}
}