Instantiation refers to the process of creating an instance of a class in Java. It allocates memory for a new object and returns a reference to that memory. Instantiation allows us to utilize objects and access class members.
Why Instantiate Objects?
Here are some key reasons for instantiating objects in Java:
- Reusability – Classes provide reusable code templates to instantiate objects with the same characteristics easily. We don‘t have to write the same code again and again.
- Real-world modeling – Objects can effectively model real-world entities with characteristics mapped to data members and behaviors to methods.
- Modular programming – Objects promote modular programming where each object encapsulates logic independently. This improves organizing and troubleshooting code.
- Data hiding – Objects allow data hiding by making members private and public. This enforces better access control to sensitive data.
- Polymorphism – Child classes can override parent class methods. Different object types can expose their own versions of the same method call.
Instantiation Syntax
We instantiate a Java object with the new
keyword. Here is the syntax:
ClassName objectName = new ClassName();
This syntax consists of three main parts:
- ClassName – The name of the class from which the object will be created
- objectName – A name to reference the new object instance
- new ClassName() – The Java new operator with constructor invocation
Let‘s looks at examples of object instantiation in Java with different scenarios.
Instantiate Single Object from a Class
Let‘s see how to instantiate an object from the Employee
class.
We first define an Employee
class with two data members and a method:
public class Employee {
int id;
String name;
void displayDetails() {
System.out.println(id + " " + name);
}
}
Next, we instantiate Employee
in MainClass
:
public class MainClass {
public static void main(String[] args) {
// Instantiating object
Employee emp = new Employee();
// Access fields and method
emp.id = 101;
emp.name = "John";
emp.displayDetails();
}
}
This instantiates emp
object and accesses class members.
Output:
101 John
Instantiate Multiple Objects of a Class
We can also create multiple objects of a class. For example:
public class MainClass {
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1.id = 1;
emp1.name = "John";
emp2.id = 2;
emp2.name = "Fiona";
emp1.displayDetails();
emp2.displayDetails();
}
}
This instantiates two Employee
objects emp1
and emp2
.
Output:
1 John
2 Fiona
Instantiate Object Using Constructors
For instantiating an object, we invoke the class constructor. It lets us initialize data members while allocating memory.
Here is an Employee
class with a parameterized constructor:
public class Employee {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
}
Creating an object now initializes parameters through the constructor:
public class MainClass {
public static void main(String[] args) {
Employee emp = new Employee(101, "John");
emp.display();
}
}
Output:
101 John
This passes arguments 101 and "John" to instantiate emp
object.
Constructors simplify instantiating objects with property values.
Instantiate as Class Member Object
Now let‘s explore instantiating an object as a member of another class.
Here is an Address
class with some data members:
public class Address {
String street;
String city;
String state;
}
Let‘s instantiate Address
within in Employee
class:
public class Employee {
int id;
String name;
Address address; // Address member
Employee(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
}
We instantiate both classes in MainClass
:
public class MainClass {
public static void main(String[] args) {
Address add = new Address();
add.street = "XYZ Street";
add.city = "ABC City";
add.state = "State A";
Employee emp = new Employee(101, "John", add);
System.out.print("Id: " + emp.id);
System.out.print(", Name: " + emp.name);
System.out.print(", Street: " + emp.address.street);
System.out.println(", City: " + emp.address.city);
}
}
Output:
Id: 101, Name: John, Street: XYZ Street, City: ABC City
This demonstrates composition by instantiating member object Address
.
Comparison to Object Cloning
Instantiation differs from object cloning in Java:
- Instantiation creates a new instance from the class
- Cloning copies an existing object to create an exact duplicate
For example, if emp
is an existing Employee
object:
// Instantiation
Employee newEmp = new Employee();
// Cloning
Employee cloneEmp = emp.clone();
So instantiation constructs a fresh object while cloning replicates an object.
When is Instantiation Used?
Here are some common use cases of instantiating objects in Java:
- Creating instances inside methods to perform business logic on objects
- Instantiating multiple objects in a collection to represent data
- Generating object instances dynamically as application executes
- Creating object copies rather than passing actual objects for thread safety
- Initializing configuration or context objects during startup processes
- Constructing mock object instances for unit testing needs
Conclusion
We learnt how to instantiate objects in Java using the new
operator and constructors. Instantiation gives several benefits like modular and reusable code. It also models real-world entities well through object properties and actions. Additionally, we covered instantiating in various scenarios with single, multiple, member and mock objects. This provides a great foundation to start building Java programs using object instances.