原文地址:http://www.javawxs.com/index.php/this-in-java/
在java程序中this关键字随处可见,用处也比较多;或许很多人对this理解不够清楚。下面我将结合例子程序总结一下this的用法。 主要分为四个小部分。
第一、调用类中的属性(this.属性)。
- package com.javawxs;
- public class PersonInformation {
- String name;
- String address;
- int age;
- PersonInformation(String name, String address, int age) {
- this.name = name;
- this.address = address;
- this.age = age;
- }
- }
在PersonInformation()方法中,可以直接访问对象的成员变量,但是在同一范围内,不允许定义两个名字相同的局部变量,那么就需要一种方法将成员变量和跟她同名字的方法的参数区分出来,这时候就可以使用this;在上边的例子程序里this在方法体中指向引用当前方法的对象实例,用this.属性来调用类中的属性。最为常见的就是在setter()和getter()中的使用。
第二、调用类中的方法(this.方法())。
- package com.javawxs;
- import java.util.Random;
- public class PersonInformation {
- int i = new Random().nextInt(200);// 产生一个随机数
- public int getI() {
- return i;
- }
- public boolean greaterthan100() {
- if (this.getI() > 100) {
- return true;
- }
- return false;
- }
在greaterthan100()方法中通过this.getI()来调用当前方法的对象实例中的getI()方法,当然这个例子中的this也可以省略。
第三、表示当前对象:this。
- class A {
- public A() {
- new B(this);
- }
- }
- class B {
- A a;
- public B(A a) {
- this.a = a;
- }
- }
这个小程序中,B的构造方法的参数为A的实例;在A中创建B的实例时将this作为A的的实例传给B的构造方法。new B(this)相当于new B(new A()) 。
第四、调用当前类中的构造方法:this()。
在构造方法使用this(参数表)就会调用同一个类中的另一个相对应的构造方法。以下是一个很典型的例子程序。
- package com.javawxs;
- public class Tester {
- int var;
- // 构造方法一
- Tester() {
- System.out.println(“good-bye”);
- }
- // 构造方法二
- Tester(String s) {
- this();
- System.out.println(s);
- }
- // 构造方法三
- Tester(int var) {
- this(“hello”);
- }
- // 构造方法四
- Tester(double var) {
- this.var = (int) var;
- }
- public static void main(String[] args) {
- Tester t = new Tester(5);
- }
- }
以上程序的执行结果是:
good-bye
hello
在构造方法中使用this(参数表)还需要注意三个问题:
1、错误示例:
- Tester(String s) {
- System.out.println(s);
- this();
- }
调用另一个构造函数的语句必须在最起始的位置。
2、错误示例:
- public void mytest(){
- this(“hello”);
- }
不能在构造函数以外的任何函数内调用构造函数。
3、错误示例:
- Tester(String s) {
- this();
- this(“hello”);
- System.out.println(s);
- }
在一个构造函数内只能调用一个构造函数。