Creating objects of a class in java

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 or instantiate 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();

/*
 * Class and object java example
 */
//user defined class
class Car {

	void run() {
		System.out.println("Car is running...");
	}
}

// Test
public class Sample {

	public static void main(String[] args) {

		// Create a reference variable of class type Car
		// and create an object of Car using new keyword

		Car maruti = new Car();

		// Call car function using object maruti with dot operator
		maruti.run();
	}

}

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++

Related Posts