How to Create an Object in Java
An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions and the member variables defined in a class can be accessed using the objects of that class. In other words, we can say that class is a blueprint or template to create objects.
The new keyword is used to create an object. Creating an object of a class is also known as instantiation. An object can be either static, non-static, or final. An object is treated as a variable of a class.
Creating a Class
To create an object and use the methods and functions of the class, we have to create a class first.
Syntax:
class class_name{
//member variables
[access_specifier] data_typevariable_name;
//member functions
[access_specifier] return_typefunction_name(arguments){
//data
}
}
Creatingan Object
There are six ways to create an object in the Java:
- Usingthe new keyword
- Using theClass.forName()
- Using the clone() method
- Using the newInstance() method of Constructor class
- Using Deserialization
Let’s understand each way one by one:
- Using the new keyword:
It is the most common way to create an object of the class in Java. The new operator instantiates the class and dynamically (at run time) allocates the memory for that object in a heap. The new operator then returns a reference to that memory and that reference is stored in the object we have created.