使用"这个"带有构造函数的关键字 - "这个"参考Point对象?

时间:2014-06-25 21:53:06

标签: java this

我正在接受此Oracle online java class并且不明白本例中的内容是如何引用

origin = new Point(0,0); 

对象。

Rectangle类的第一个例子。

public class Rectangle {

public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing the area of the rectangle
    public int getArea() {
    return width * height;
    }

}

使用this关键字的Rectangle示例。

public class Rectangle {
private int x, y;
private int width, height;

public Rectangle() {
    this(0, 0, 1, 1);
}
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;
}
...
}

第二个例子在哪里引用了origin = new Point(0,0)对象?

public class Point {
// TODO Auto-generated method stub
        public int x = 0;
        public int y = 0;
        // a constructor!
        public Point(int a, int b) {
        x = a;
        y = b;
}

}

2 个答案:

答案 0 :(得分:2)

  

如果您不添加this关键字,则默认情况下(隐式)为该类的实例成员添加。

因此,无论您是否使用this关键字,都是一样的。

请查看Understanding Class Members

阅读Using the keyword “this” in java

上的其他帖子

答案 1 :(得分:1)

看起来第二个例子没有引用Point类。

由于一些奇怪的原因,它们显然只是改变了类的工作方式,用整数x和y替换了“Point”类(实际上只有两个整数)

要重写第二个类,使其实际上与第一个类相同,您可以按如下方式编写:

public class Rectangle {
private Point origin;
private int width, height;

public Rectangle() {
    this(new Point(0,0), 1, 1);
}
public Rectangle(int width, int height) {
    this(new Point(0,0), width, height);
}

//One more constructor just for fun
public Rectangle(int x, int y, int width, int height) {
    this(new Point(x, y), width, height);
}

//Note: All of the constructors are calling this method via this(Point, int, int)
public Rectangle(Point origin, int width, int height) {
    this.origin = origin;
    this.width = width;
    this.height = height;
}
...
}