Creating & Initializing Objects in Java With new Keyword
1. Creating an Object
The new keyword creates an object (instance) of a class.
Point origin = new Point(23, 94);
Here:
new Point(23, 94)
↓
creates a Point object
↓
constructor is called
↓
reference is returned
↓
stored in origin
Instantiating a class = creating an object (instance) of that class.
2. Constructor
A constructor:
-
Has the same name as the class
-
Has no return type
-
Is called automatically when using
new -
Initializes the object's data
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Point p = new Point(10, 20);
3. Multiple Constructors
A class can have multiple constructors as long as their parameter lists are different.
class Rectangle {
Rectangle() {
}
Rectangle(int width, int height) {
}
Rectangle(Point origin, int width, int height) {
}
}
This is called constructor overloading.
Java chooses the constructor based on the number and types of arguments.
new Rectangle(); // Rectangle()
new Rectangle(50, 100); // Rectangle(int, int)
new Rectangle(p, 50, 100); // Rectangle(Point, int, int)
4. No-Argument Constructor
A constructor with no parameters is called a no-argument constructor.
Rectangle rect = new Rectangle();
If you don't define any constructor, Java automatically provides a default no-argument constructor.
class Rectangle {
// Java provides Rectangle() automatically
}
Important: If you define your own constructor, Java does not automatically provide the no-argument constructor.
5. Object References
A variable of an object type stores a reference to the object, not the object itself.
Point p = new Point(10, 20);
Multiple variables can refer to the same object:
Point p1 = new Point(10, 20);
Point p2 = p1;
Now:
p1 ──┐
├──→ Point object
p2 ──┘
Changing the object through p2 also affects what p1 sees.
Quick Summary
new
↓
Creates object
↓
Calls constructor
↓
Returns object reference
newcreates the object; the constructor initializes it.