Last Updated on January 18, 2024 by Ankit Kochar
Java, a versatile and widely-used programming language, empowers developers to build robust and scalable applications. One fundamental aspect of Java programming is the creation and manipulation of objects. Objects are instances of classes, encapsulating data and methods to operate on that data. Understanding how to create objects in Java is fundamental for anyone venturing into the world of object-oriented programming. This guide will walk you through the process, providing insights into the essential concepts and practices for effective object creation in Java.
How to Create Object in Java?
An object is a fundamental building block in an OOPs language. We cannot run any Java program without first creating an object. Let’s see how we can create object in Java.
There are several different ways of object creation in Java:
1. Object Creation in Java Using new Keyword
This is the most common approach for creating an object. Almost all the objects are created using this method. The new keyword implicitly invokes the class’s constructor. The Constructor can be parameterized or non-parameterized. The new keyword allocates memory for the object and returns a reference to it.
Code Implementation:
class PrepBytes { public String name; PrepBytes() { name = "Hariharan"; } PrepBytes(String s) { name = s; } public static void main(String[] args) { PrepBytes obj = new PrepBytes(); PrepBytes obj1 = new PrepBytes("Himantica"); System.out.println(obj.name); System.out.println(obj1.name); } }
Output
Hariharan
Himantica
Explanation: In the above approach, we create an object obj using a default no-arg constructor, where the value of the attribute name is set to "Hariharan" by default. Then we create another object obj1 using a parameterized constructor, where it passes the value "Himantica" as an argument to the constructor.
2. Object Creation in Java Using the newInstance() method
We can create an object Class.forName if we know the name of the class and that it has a public default constructor. Class.forName loads the class in Java but does not create any object. To create an object of the class, utilize the new Instance Method of the Class.
Code Implementation:
class PrepBytes { public String name; PrepBytes() { name = "Manoj"; } public static void main(String[] args) { try { Class pb = Class.forName("PrepBytes"); PrepBytes s = (PrepBytes) pb.newInstance(); System.out.println(s.name); } catch (Exception e) { System.out.println(e); } } }
Output
Manoj
Explanation: Class.forName("PrepBytes") loads the class named "PrepBytes" and stores the reference in pb. Then, (PrepBytes) pb.newInstance() creates a new object of the loaded class.
3. Object Creation in Java Using Clone() Method
Whenever we call the clone() method on an object, the JVM creates a new object and copies all of the original object’s content into it. The clone method does not call any constructors when creating an object. To use the clone() method on an object, we must first implement Cloneable and define the clone() method.
Code Implementation:
class PrepBytes implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } String name = "I am PrepBytes"; public static void main(String[] args) { PrepBytes obj1 = new PrepBytes(); try { PrepBytes obj2 = (PrepBytes)obj1.clone(); System.out.println(obj2.name); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
Output
I am PrepBytes
Explanation: In the above approach, we are creating a clone object obj2 of an existing object obj1 and not any new object. However, the class needs to first implement the cloneable interface, otherwise, it will throw a CloneNotSupportedException.
4. Object Creation in Java Using newInstance() Method of the Constructor Class
The newInstance() method of the Constructor class is very much similar to the newInstance() method of the Class class, except that we can provide parameters for the different parameterized constructors.
Code Implementation:
import java.lang.reflect.*; class PrepBytes { private String name; PrepBytes() {} public void setName(String name) { this.name = name; } public static void main(String[] args) { try { Constructor<PrepBytes> constructor = PrepBytes.class.getDeclaredConstructor(); PrepBytes r = constructor.newInstance(); r.setName("Hello! Welcome to PrepBytes"); System.out.println(r.name); } catch (Exception e) { e.printStackTrace(); } } }
Output
Hello! Welcome to PrepBytes
Explanation: In the above approach, the main method of the class demonstrates the use of the newInstance() method of the Constructor class to create an object of the PrepBytes class dynamically at runtime. It does so by using the getDeclaredConstructor() method of the PrepBytes class to obtain a reference to its default constructor and then calling the newInstance() method of the Constructor class to create a new instance of the class. After creating the object, the code sets the value of its name instance variable using the setName() method and then prints out the value of the name variable to the console.
5. Object Creation in Java Using Deserialization
JVM creates a new object whenever we serialize and then deserialize an object. JVM does not use a constructor to create the object during deserialization. To deserialize an object, we must implement the Serializable interface in the class.
Code Implementation:
import java.io.*; class PrepBytes implements Serializable { private String name; PrepBytes(String name) { this.name = name; } public static void main(String[] args) { try { PrepBytes d = new PrepBytes("Welcome To PrepBytes!"); FileOutputStream f = new FileOutputStream("file.txt"); ObjectOutputStream oos = new ObjectOutputStream(f); oos.writeObject(d); oos.close(); f.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output
Welcome To PrepBytes!
Explanation: In the above approach, the Java code demonstrates how to write an object of the PrepBytes class to a file using serialization. The PrepBytes class implements the Serializable interface, which means that objects of this class can be serialized, or converted to a byte stream that can be stored in a file or transmitted over a network.
The PrepBytes class has a private instance variable called name and a constructor that initializes this variable. The main method of the class creates a new PrepBytes object and writes it to a file called file.txt using the ObjectOutputStream class. This is done by creating a new FileOutputStream to write the serialized data to a file and then wrapping it with an ObjectOutputStream to write the object to the stream. Finally, the output stream and file streams are closed.
Conclusion
In conclusion, mastering the art of creating objects in Java is a pivotal step towards becoming proficient in object-oriented programming. As we’ve explored in this guide, the process involves defining classes, instantiating objects, and utilizing constructors to initialize object properties. Additionally, we’ve delved into concepts like encapsulation and inheritance, which enhance the flexibility and maintainability of Java code. Armed with this knowledge, developers can architect well-organized and scalable applications, leveraging the power of objects to model real-world entities effectively.
FAQs related to How to Create Object in Java
Here are some FAQs related to the topic of how to create object in Java:
1. What is an object in Java?
In Java, an object is an instance of a class that encapsulates data and methods to manipulate that data. Objects are the building blocks of object-oriented programming, allowing developers to model real-world entities and their behaviors.
2. How do you create an object in Java?
To create an object in Java, you need to follow these steps:
- Define a class that serves as a blueprint for the object.
- Use the new keyword followed by the class constructor to instantiate the object.
- Optionally, initialize the object’s properties using constructors or setter methods.
3. What is a constructor in Java, and why is it essential for object creation?
A constructor in Java is a special method used to initialize the state of an object. It has the same name as the class and is called when an object is created. Constructors are crucial for object creation as they ensure that objects start with a valid and consistent state.
4. Can you create objects without using a constructor in Java?
In Java, every class has a default constructor provided by the compiler if no constructor is explicitly defined. However, defining your constructors allows you to control how objects are initialized, providing more flexibility in object creation.
5. How does encapsulation contribute to effective object creation in Java?
Encapsulation is a concept in Java that involves bundling data and methods that operate on that data within a single unit, i.e., a class. This enhances data security and integrity and makes the code more modular. Effective use of encapsulation contributes to creating well-organized and maintainable objects in Java.