Java Reference
In-Depth Information
constructor executes when the client uses the
new
keyword to create a new object.
When you write a constructor, you specify what parameters must be passed when
clients use the
new
keyword with your type and how those parameters should be used
to initialize the newly created object.
A constructor's header begins with the keyword
public
, followed by the class's
name and any parameters. It looks like a method header with the same name as the
class, except that you do not specify a return type. A constructor often has parameters
that specify the object's initial state. Our constructor for the
Point
class will accept
initial x and y values as parameters and store them into the new
Point
object's
x
and
y
fields:
// constructs a new point with the given (x, y) location
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
Like instance methods, constructors execute on a particular object (the one that's
being created with the
new
keyword) and can refer to that object's fields and methods
directly. In this case, we store
initialX
and
initialY
parameter values into the
new
Point
object's
x
and
y
fields:
Point p1 = new Point(7, 2);
x
x 3
y
p1
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
Now that we are exploring constructors, it makes sense to think about the process
of creating objects in more detail. When an executing Java program reaches a state-
ment that creates a new
Point
object, several operations occur:
Search WWH ::
Custom Search