Java is an Object-oriented language. In other words, almost everything in Java is treated as an object. Hence, while programming in Java, one should know all possible ways of creating objects in Java. But before diving deeper into objects, you must know the concept of Java Classes and how objects are related to them.
In this post, we will cover 5 different ways to created objects in Java and understand all essential concepts required to understand the methods.
- Create objects using ‘new’ keyword
- Create objects Using clone( ) method
- Create objects using the newInstance( ) method of class
- Create objects using deserialization
- Create objects using the newInstance( ) method of constructor class
Let’s get started.
Create objects using ‘new’ keyword
While programming in Java you might’ve definitely come across the ‘new’ keyword. It is a keyword used to create an object which is dynamically allocated memory i.e memory to these objects is assigned at runtime. And this dynamic allocation is required most of the time while creating objects. Hence this method is used more often than others.
Syntax: ClassName ObjectName = new classConstructor( );
public class ObjectCreation { String FirstString = "Hello World"; public static void main(String[] args) { ObjectCreation obj = new ObjectCreation(); System.out.println(obj.FirstString); } }
Output- Hello World
This method of creating objects in Java can be used with any constructor of the required class if the class is having more than 1 constructor.
Create Objects using clone( ) method
What if the object that we want to create should be a copy of an already existing object? In that case, we can use the clone( ) method. clone( ) is a part of the Object class but it cannot be used directly as it is a protected method.
clone( ) method can only be used after implementing the Cloneable interface and handling CloneNotSupportedException.
class Message implements Cloneable { String FirstString; Message() { this.FirstString = "Hello World"; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class ObjectCreation { public static void main(String[] args) throws CloneNotSupportedException { Message FirstObj = new Message(); System.out.println(FirstObj.FirstString); Message SecondObj = (Message)FirstObj.clone(); System.out.println(SecondObj.FirstString); SecondObj.FirstString = "Welcome to the world of programming"; System.out.println(SecondObj.FirstString); System.out.println(FirstObj.FirstString); } }
Output-
Hello World
Hello World
Welcome to the world of programming
In the above program, we created a copy of our already existing object. To make sure both the variables are not pointing to the same memory location it was essential to change the value of ‘FirstString’ for the second object and then print its value for both objects.
Create objects using the newInstance( ) method of class Class
This method is not used often for creating objects. This method of creating an object is used if we know the class name and the default constructor is public in nature. To use this method for creating objects we need to handle 3 exceptions
ClassNotFoundException- This exception occurs if the JVM is unable to find the class which is passed as an argument.
InstantiationException- This exception occurs if the given class does not contain a default constructor.
IllegalAccessException- This exception occurs if we don’t have access to the specified class.
Once we take care of these exceptions we are good to go.
class ObjectCreation{ String FirstString = "Hello World"; public static void main(String[] args) { try { Class Message = Class.forName("ObjectCreation"); ObjectCreation obj = (ObjectCreation) Message.newInstance(); System.out.println(obj.FirstString); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
Create objects using deserialization
In Java Serialization is used to convert the current state of an object into a byte stream. deserialization is the exact opposite as we recreate the object using the byte stream. For the process of serialization, we need to implement Serializable interface. Exception Handling is to be done to create objects using this method.
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); Classname object = (classname) objectInputStream.readObject();
Create Objects using newInstance( ) method of Constructor class
We saw the newInstance method of class Class which we used to create an object. Similarly, the class constructor also consists of a newInstance( ) method which can be used to create objects. Other can default constructors with the help of this method we can also call parameterized constructors.
import java.lang.reflect.*; public class ObjectCreation { private String FirstString = "Hello World"; ObjectCreation() { } public void changeMessage(String message) { this.FirstString = message; } public static void main(String[] args) { try { Constructor<ObjectCreation> constructor = ObjectCreation.class.getDeclaredConstructor(); ObjectCreation objectCreation = constructor.newInstance(); objectCreation.changeMessage("Welcome to the world of programming"); System.out.println(objectCreation.FirstString); } catch (Exception e) { e.printStackTrace(); } } }
Output-
Welcome to the world of programming
These are 5 different ways of creating objects in Java some are used more often than others. Each method has its own advantages and disadvantages. In the end, the choice is yours.
Java is an interesting language, but it becomes tricky if the fundamentals are not clear. To kick-start, your learning and master all the skills related to java technology enroll to the Java Certification Program and unleash the java developer in you.
Got a question for us? please mention this in the comments section of this ‘objects in Java’ article and we will get back to you as soon as possible.