关键字this表示每个实例对象指向自己的引用,
可以出现在实例方法和构造方法中,
不能出现在有static修饰的类方法(即静态方法)中。
1 在实例方法和构造方法中使用this
this可以出现在类的构造方法和非static修饰的成员方法(即实例方法中),this代表实例对象自身,可以通过this来访问实例对象的成员变量或者调用成员方法。
【例:5-5】使用this访问成员变量 或 通用成员方法。
package EXthis;
public class Ex5_5_this1 {
public static void main(String[] args) {
Cat garfield = new Cat("黄",12);
System.out.println("对象已被实例化。");
garfield.grow();
System.out.println("grow()方法第 1 次被调用执行完毕。");
garfield.grow();
System.out.println("grow()方法第 2 次被调用执行完毕。");
}
}
class Cat{
String furColor;
int height;
public Cat(String color){
this.furColor = color; // 通过this访问成员变量,this可以省略
this.cry();// 通过this调用成员方法这里this可以省略
}
public Cat(String color,int height){
this(color);
// 通过this调用其他构造方法,即之传入例如color参数的构造方法
this.height = height; // this可省略
}
public void cry() {
System.out.println("我是一只" + furColor + "颜色的猫");
}
public void grow() {
height++;
System.out.println("我长高了,身高为:" + height);
// this可省略 一省略
}
}
运行结果:
2.区分成员变量和局部变量
成员变量在整个类中有效,局部变量仅在方法中有效。
在方法体中声明的变量 以及方法的传入参数均称为局部变量,局部变量只在方法体内有效。
如果实例方法中(即成员方法) 或类方法中局部变量名字与成员变量相同,那么这个成员变量在这个方法内暂时失效。如果确实相比引用成员变量,则可使用this关键字。
如下:
package com.ch5;
public class Ex5_6_this2 {
public static void main(String[] args){
Ex5_6_this2 e = new Ex5_6_this2();
e.f();
}
int x = 188,y,z=9;
void f(){
int x = 3;
y = x; // y得到的值是3,而非第4行的成员变量 188
System.out.println("y = " + y);
y = this.x;
System.out.println("y = " + y);// 成员变量x的值 188
System.out.println("z = " + z);// 9
}
}
3.返回实例对象本身的引用
this还可以作为类成员方法的return语句的参数,用来返回对象本身的引用。
【例5-7】
package com.ch5;
public class Ex5_7_this3 {
public static void main(String[] args){
Dog tom = new Dog();
System.out.println("新生的tom的身高为:"+ tom.height
+ "cm,年龄为:" + tom.age);
tom = tom.grow();
System.out.println("长大后tom的身高为:"+ tom.height
+ "cm,年龄为:" + tom.age);
}
}
class Dog{
int age;
float height;
public Dog(){
age = 1;
height = 10;
}
public Dog grow(){
height = height + 10;
age++;
return this;
}
}
4.在类的构造方法中,可以使用this() 来调用该类的其他构造函数,具体哪个构造函数根据括号里的参数来判断
【例5-8】
package com.ch5;
public class Ex5_8_this4 {
public static void main(String[] args) {
Annimal a = new Annimal(10,20);
System.out.println("新生小动物");
System.out.println("age = "+a.age+ "\t weighrt=" + a.weight
+"克\t height = " + a.height + "cm") ;
}
}
class Annimal{
int age;
String furCorlor;
String eyeColor;
String name;
float weight;
float height;
public Annimal(float height){
this.age = 1;
this.height = height;
}
public Annimal(String name){
this.age = 1;
this.name = name;
}
public Annimal(float height,float weight){
this(height);
// A 使用this调用了上面第一个构造函数public Annimal(float height)
this.weight = weight;
}
}
重点是A 行 height的类型是float
5.类方法中不可以使用this
由于类方法可以通过类名直接调用,这是可能还没有任何对象产生,因此指代对象实例的this关键字不可以出现在类方法中。
综上所述,关键字this可以出现的类的构造方法和非static修饰的成员方法(实例方法)中,指代对象自身,有以下几种使用情况。
(1) 在类的成员方法中,可以通过this来访问实例对象的成员变量或调用成员方法。
(2)在类的成员方法中,区分成员变量和局部变量。
(3)在类的成员方法中,使用this返回实例对象本身的引用。
(4)在类的构造方法中,用this()调用该类的其他构造方法。