Class is a user-defined data type which is naturally used to declare objects of that type. So, an object is a real-world entity, having a set of attributes and behavior. However, an object can’t be simply declared as same as primitive types.
In Java, creation of an object is a two-step procedure where we first declare an object of that class type and then a physical copy of the actual object of the class is assigned to that variable.
This assignment of an actual copy of the object is done by using ‘new keyword’ for dynamic allocation of memory. A ‘new keyword’ allocates memory in heap and a reference to the allocated object which is nothing but an address is stored in the variable of the respective reference type.
Syntax:
Myclass obj; // Not an object, just a reference variable Obj = new Myclass(); // instantiation and initialization object
Each time when an object is declared, it is said to be an instance of a class is created.
An object gets memory on the heap. In stack memory, the variable of class type stores the address of an object.
In heap memory, a physical copy of an object is stored and the reference or address of this copy in the variable of the associated class. Objects that can no longer be referenced are cleaned up by Garbage collector.
class myclass{ void display(){ System.out.println("I am printing"); } } public class Sample1 { public static void main(String[] args) { myclass obj; obj= new myclass(); obj.display(); } }
Output:
I am printing
This post was last modified on September 29, 2020