原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/11/28/2793257.html

在一个实例方法或者是构造方法中,this引用指向当前的对象---方法调用或者是构造方法调用的对象。你可以在实例化方法或者构造方法中,使用this引用任何成员。

 

在字段中使用this

使用this关键字的最常见的原因,是字段被方法或构造函数的参数隐藏了。

例如,Point类是这样写的:

public class Point {
    public int x = 0;
    public int y = 0;
        
    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

但是它也可以这么写:

public class Point {
    public int x = 0;
    public int y = 0;
        
    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}


构造方法的每个参数都隐藏了对象的字段---在构造方法里,x是构造方法的第一个参数的局部副本,引用Point字段x,构造方法必须使用this.x.

 

在构造方法使用this

在构造方法里,你可以使用this关键字调用类的另一个构造方法。这种是显式构造方法调用。这里有一个Rectangle类:

public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}


这个类有一系列构造方法,每个构造方法初始化Rectangle的部门变量。如果没有为参数提供初始化值,构造方法为每个成员变量提供了默认值。例如,无参构造方法,传入四个值为0的参数,调用四个参数的构造方法,还有两个参数的构造方法,传入两个0的参数,调用四个参数的构造方法。之前说过,编译器是根据参数的个数和类型,决定调用哪个构造方法。

 

如果存在,另一个构造函数的调用必须是构造函数中的第一行。

相关文章:

  • 2021-09-07
  • 2022-01-08
  • 2021-10-21
  • 2021-08-20
  • 2021-09-07
  • 2021-07-07
猜你喜欢
  • 2021-12-20
  • 2022-02-09
  • 2022-01-04
  • 2021-10-30
  • 2021-12-19
  • 2022-02-27
相关资源
相似解决方案