CreateObjectDemo
program creates an object and assigns it to a variable:
Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);
Point
class,
and the second and third lines each create an
object of the
Rectangle
class.
Each of these statements has three parts (discussed in detail below):
type name;
You can also declare a reference variable on its own line. For example:
Point originOne;
originOne
like this, its value will be undetermined
until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.
For that, you need to use the new
operator,
as described in the next section. You must assign an object to originOne
before you use it in your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object,
can be illustrated as follows (the variable name, originOne
,
plus a reference pointing to nothing):
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:
Point originOne = new Point(23, 94);
int height = new Rectangle().height;
public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } }
Point originOne = new Point(23, 94);
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; } }
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle
's constructors that
initializes origin
to originOne
.
Also, the constructor sets width
to 100 and
height
to 200.
Now there are two references to the same Point object—
an object can have multiple references to it, as shown in the next figure:
Rectangle
constructor that requires two
integer arguments, which provide the initial values for width
and height. If you inspect the code within the constructor,
you will see that it creates a new Point object whose x
and y values are initialized to 0:
Rectangle rectTwo = new Rectangle(50, 100);
Rectangle rect = new Rectangle();
Object
constructor if the class has no other parent.
If the parent has no constructor (Object
does have one), the compiler will reject the program.