I need to know the order, in which the constructors will be called.
Point class:
public class Point
{
public int x = 0;
public int y = 0;
// a constructor!
public Point(int a, int b) {
x = a;
y = b;
}
}
Rectangle class:
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;
}
}
A class which creates objects:
public class CreateObjectDemo {
public static void main(String[] args) {
//Declare and create a point object
//and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());
rectTwo.origin = originOne;
}
}
-
In which order are the constructors in class Rectangle called?
-
When will the
public Rectangle(Point p)be called? -
What does the statement
rectTwo.origin = originOnedo ?
The program is from Oracle’s Java Tutorial site.
In general, the control flow is in program order (i.e. left-to-right), with the following exceptions:
Thus we have the following order:
Point originOne = new Point(23, 94);– this will call thePointconstructor.Rectangle rectOne = new Rectangle(originOne, 100, 200);– this will call theRectangleconstructor with a Point and twointarguments.Rectangle rectTwo = new Rectangle(50, 100);– this will call theRectangleconstructor with twointarguments.origin = new Point(0, 0);call thePointconstructor.There are no more explicit constructor calls. But each of these calls includes an implicit call to the constructor of its superclass (which is
Objecthere) at the start.The constructor
Rectangle(Point)is not called at all, it seems.rectTwo.origin = originOne;changes the origin of the second rectangle from (0,0) to the same point which is used byrectOne, e.g. (23,94).