Object Creation in Java
--
Student bob = new Student();
This is how we usually create an object in Java.
As Java doc says, we can break this statement into three parts:
- Declaration
- Instantiation
- Initialization
1. Declaring a variable to refer an object
Student bob;
In here we declare reference variable bob
of type Student
.
Declaring a reference variable does not create object. At this state bob
references to nothing. It’s value will be undetermined until we create an object and assign to it.
2. Instantiating a class
The new
keyword is a Java operator that:
- Instantiates a class by allocating memory for a new object on the heap at runtime.
- Returns a reference to that memory.
- Invokes the object constructor.
We have to provide a postfix argument to the new
operator. The argument is the constructor name whose class we are going to instantiate.
Student bob = new Student();
In here we are going to instantiate or create an object of Student class.
The new
operator returns a reference to the object it created. This reference is stored to a variable of the appropriate type. In our example bob
will store the newly created object’s reference.
NOTE: Instantiating a class means the same thing as creating an object. When you create an object, you are creating an instance of a class.
3. Initiating an object
Constructors initialize the instance variables associated with its class. So that constructors can also be called as initializers. Instance variables will be initialized to their default values if not explicitly defined by the programmer.
Constructors initialize those variables from inside out (The constructors are executed from all the way up the inheritance hierarchy to down).
It goes all the way up to the Object class and comes back down. While coming down, it initializes all those variables.