Creating objects of a class in java

(Last Updated On: February 26, 2019)

Class and object java example – Learn how to create a class and object in java programs with example. Also, know how and where objects and its references are stored in memory i.e. stack and heap and its de – allocation.

We have understood what is class in java and how to write it in in detail. Now understand how we create an object of a class in a java program.

Consider a class is Car and it contains one method run().

To create an object of Car class, we will use new keyword. For example, here we have created one object of Car called Maruti.

Car Maruti = new Car();

 

NOTES:

Car Maruti; => reference is created on stack.

new Car(); => Create object of Car on Heap and address of it is assigned to Maruti reference.

 

Similarly, we can create multiple objects of class Car. for example,

Car Honda = new Car();

Car ford = new Car();

 

In the above java class and object example program, when Maruti reference goes out of scope, meaning, when main() method ends, reference Maruti will be cleaned from stack and the object resides on Heap will be eligible for garbage collection.

Meaning JVM will clean the object and we don’t have to de- allocate it manually / explicitly like we do in in C++