15-面向对象-this关键字
this关键字
Java虚拟机会给每个对象分配 this,代表当前对象。
a) 如果出现在构造器中:表示正在创建的对象
b) 如果出现在成员方法中:表示正在调用这个方法的对象
//this关键字 public class This01 { public static void main(String[] args){ Dog dog1 = new Dog("大壮",3); dog1.info(); } } class Dog{ //属性(成员变量,局部变量) String name; int age; //构造器(没有this关键字) public Dog(String cName, int cAge){ name = cName; age = cAge; } /* * * 如果构造器的形参,能够直接写出属性名,就更直接了。但出现了一个问题,根据变量的作用域原则 * 构造器的形参列表(String name, int age) name和age 是局部变量,而不是属性,只能作用于方法体内 * * 这里引出 this关键字 解决 ,this代表当前对象 * * */ //构造器(this关键字) public Dog(int age, String name){ //this.age 就是当前对象的age属性 this.age = age; //this.name 就是当前对象的name属性 this.name = name; } //成员方法(this关键字) public void info(){ System.out.println("当前对象的名字:" + this.name + "\t当前对象的年龄:" + this.age); System.out.println("当前对象的hashCode是:" + this.hashCode()); } }
this的用法
1) this.属性
当局部变量与属性同名时,那么可以在属性的前面加“this.”用于区别
2) this.方法名(参数列表)
调用当前对象的成员方法,但这里也可以省略“this.”
3) this() 或 this(实参列表)
this() 表示调用本类的无参构造方法
this(实参列表) 表示调用本类的有参构造方法
这里需要注意:this() 或 this(实参列表) 只能在构造器中使用,要么没有,要么必须出现在构造器的首行,这是因为对this() 或 this(实参列表) 的调用必须是构造器中的第一个语句
public class This02 { public static void main(String[] args){ Student stu = new Student("马铃薯",90); } } class Student{ private String name; private int score; //显示定义,默认的构造器 public Student(){ } //第一个构造函数(this关键字) public Student(String name){ this.name = name; System.out.println("====调用第一个构造函数===="); } //第二个构造函数(this关键字) public Student(String name, int score){ //this(实参列表) 表示调用本类的有参构造方法 //这里需要注意,对this() 或 this(实参列表) 的调用必须是构造器中的第一个语句 this(name); System.out.println("====调用第二个构造函数===="); } }
this关键字的注意事项
this关键字只能出现在非static修饰的代码中,没有static关键字的方法称为“实例方法”,没有static关键字的变量称为“实例变量”。
这是因为一个行为/动作执行的过程当中是需要对象参与的,那么这个方法一定要定义为“实例方法”,不要带static关键字.
a) 在带有static的方法当中,不能“直接”访问实例变量和实例方法。实例变量和实例方法都需要对象的存在(new),比如 Student stu = new Student();
而static方法当中是没有this的,也就是说当前对象是不存在的,自然也是无法直接访问当前对象的实例变量和实例方法。
b) 在不带有static的方法中可以使用this关键字访问实例变量/实例方法.
练习题 定义一个Person类,里面有name、age属性,并提供compareTo比较方法,用于判断是否和另一个人相等,提供测试类TestPerson用于测试,如果名字和年龄完全一样,则返回true,否则返回false
public class TestPerson { public static void main(String[] args){ Person p1 = new Person("马铃薯",26); Person p2 = new Person("土豆",26); boolean res = p1.compareTo(p2); System.out.println("两个人的比较结果:" + res); } } /* * 定义一个Person类,里面有name、age属性,并提供compareTo比较方法,用于判断是否和另一个人相等, * 提供测试类TestPerson用于测试,如果名字和年龄完全一样,则返回true,否则返回false * * */ class Person{ String name; int age; //构造器 public Person(String name, int age){ this.name = name; this.age = age; } //比较方法 public boolean compareTo(Person p){ //判断名字和年龄是否一样 if(this.name.equals(p.name) && this.age == p.age){ return true; }else{ return false; } } }