this关键字的使用:
java当中this关键字的四个用法:
1、this关键字可以调用当前类的属性。
2、this关键字可以调用当前类的方法。
3、this关键字可以调用当前类的构造方法。类当中有多个构造方法调用构造方法的时候必须在构造方法的首行进行调用。
4、this关键字能够表示当前对象本身。
范例:this关键字调用当前类的属性、方法和构造方法
package obc06;
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat(){
System.out.println(age+"岁"+name+"正在吃饭");
}
public Person(int age, String name) {
this();
this.age = age;
this.name = name;
System.out.println("这是一个有参的构造方法");
this.eat();
}
public Person() {
super();
System.out.println("这是一个无参的构造方法");
}
public Person(int age){
System.out.println("这是一个只有一个参数的构造方法");
this.setAge(age);
}
}
//以下是实际测试类
package obc06;
public class OopDemo01 {
public static void main(String[] args) {
Person p = new Person(23,"小王");
}
}
范例:this关键字可以表示当前对象本身(一般来说用于对象之间的比较)
public void compare(Person p){
if(this.equals(p)){
System.out.println("两个对象相同");
}else{
System.out.println("两个对象不同");
}
}
package obc06;
public class OopDemo01 {
public static void main(String[] args) {
Person p = new Person(23,"小王");
Person p1 = new Person(23,"小王");
p1.compare(p);
}
}
测试类的代码运行结果发现就算年龄和姓名一致的两个对象,也无法判断两个对象相同,原因在于没有覆写的equals()本身只默认比较对象的地址。
下篇讲static关键字的使用!



