我正在接受此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;
}
}
答案 0 :(得分:2)
答案 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;
}
...
}