Object Creation in Java

Bindu Shrestha
3 min readSep 18, 2021

--

Classes and objects are the fundamentals in java. Having a good understanding of how objects are created is essential for object oriented programming.

new Operator

new is a keyword in java that is used to create new object as the name suggests. What it does is allocate memory for the new object and returns a reference to it. So when we say object is created, that basically means memory is allocated for the object.

Let’s take a example of a Cat class:

Cat mimi = new Cat();

In the above line, when java sees the variable mimi, it allocates memory for it and this memory is going to store reference to Cat object. It’s only when it sees the new keyword it allocates the memory for the Cat object in a section called heap, which would have space for our variable ‘name’ and ‘color’ in Cat class. Also note that creating an object is same as creating an instance of the class hence it’s also called instantiating a class.

When instantiating a class, new keyword is followed by constructor, which is same as init() method in other languages used to initialize variables in the class. If we do not pass any parameter to the constructor, instance variables are assigned default values as in our case.

There are some interesting points to note about constructor:
1. If our class does not have any constructor, compiler will add a constructor with no parameter called default constructor. So in our Cat class above, compiler will add a default constructor.

2. If our class extends from any other class, first line in the constructor must be call to parent class constructor or constructor of same class.

This means that when creating objects, initialization happens from the inside out. When we call the Cat() constructor the first line super() will call the Animal() constructor, and Object() constructor will be called in turn. So the first constructor to be executed is of the Object class, the call returns to the Animal constructor which gets executed and finally the Cat constructor will be executed.

Calling constructor of same class or parent class after any other lines of code will give compile time error. Following will give compile time error:

3. Another important point is that every class in java directly or indirectly inherits from Object class. Compiler add this code automatically.

--

--

Responses (2)