How to Create Object in Java

How to Create Object in Java – The object is a basic building block of an OOPs language. In Java, we cannot execute any program without creating an object. There is various way to create an object in Java that we will discuss in this section, and also learn how to create an object in Java.

Table of Contents

Objects in Java

Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

If we consider a dog, then its state is – name, breed, color, and the behavior is – barking, wagging the tail, running.

If you compare the software object with a real-world object, they have very similar characteristics.

Software objects also have a state and a behavior. A software object’s state is stored in fields and behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Java provides five ways to create an object.

  • Using new Keyword
  • Using clone() method
  • Using newInstance() method of the Class class
  • Using newInstance() method of the Constructor class
  • Using Deserialization

Using new Keyword

Using the new keyword is the most popular way to create an object or instance of the class. When we create an instance of the class by using the new keyword, it allocates memory (heap) for the newly created object and also returns the reference of that object to that memory. The new keyword is also used to create an array. The syntax for creating an object is:

  1. ClassName object = new ClassName();  

Let’s create a program that uses new keyword to create an object.

CreateObjectExample1.java

  1. public class CreateObjectExample1   
  2. {    
  3. void show()    
  4. {    
  5. System.out.println(“Welcome to javaTpoint”);    
  6. }    
  7. public static void main(String[] args)   
  8. {    
  9. //creating an object using new keyword   
  10. CreateObjectExample1 obj = new CreateObjectExample1();   
  11. //invoking method using the object  
  12. obj.show();    
  13. }    
  14. }   

Output:

Welcome to javaTpoint

By using the new keyword, we can also invoke the constructor (default or parametrized) of the class.

CreateObjectExample2.java

  1. public class CreateObjectExample2  
  2. {  
  3. //constructor of the class    
  4. CreateObjectExample2()    
  5. {    
  6. System.out.println(“Welcome to javaTpoint”);    
  7. }    
  8. public static void main(String[] args)   
  9. {    
  10. //creating an object using new keyword   
  11. CreateObjectExample2 obj = new CreateObjectExample2();   
  12. }    
  13. }   

Output:

Welcome to javaTpoint

Using clone() Method

The clone() method is the method of Object class. It creates a copy of an object and returns the same copy. The JVM creates a new object when the clone() method is invoked. It copies all the content of the previously created object into new one object. Note that it does not call any constructor. We must implement the Cloneable interface while using the clone() method. The method throws CloneNotSupportedException exception if the object’s class does not support the Cloneable interface. The subclasses that override the clone() method can throw an exception if an instance cannot be cloned.

Note: The method creates a copy of the object not a new object.

Syntax:

  1. protected Object clone() throws CloneNotSupportedException  

We use the following statement to create a new object.

  1. ClassName newobject = (ClassName) oldobject.clone();  

CreateObjectExample3.java

  1. public class CreateObjectExample3 implements Cloneable   
  2. {   
  3. @Override  
  4. protected Object clone() throws CloneNotSupportedException   
  5. {   
  6. //invokes the clone() method of the super class      
  7. return super.clone();   
  8. }   
  9. String str = “New Object Created”;   
  10. public static void main(String[] args)   
  11. {  
  12. //creating an object of the class     
  13. CreateObjectExample3 obj1 = new CreateObjectExample3();   
  14. //try catch block to catch the exception thrown by the method  
  15. try  
  16. {  
  17. //creating a new object of the obj1 suing the clone() method  
  18. CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();   
  19. System.out.println(obj2.str);   
  20. }   
  21. catch (CloneNotSupportedException e)   
  22. {   
  23. e.printStackTrace();   
  24. }   
  25. }   
  26. }  

Output:

New Object Created	

Using newInstance() Method of Class class

The newInstance() method of the Class class is also used to create an object. It calls the default constructor to create the object. It returns a newly created instance of the class represented by the object. It internally uses the newInstance() method of the Constructor class.

Syntax:

  1. public T newInstance() throws InstantiationException, IllegalAccessException  

It throws the IllegalAccessException, InstantiationException, ExceptionInInitializerError exceptions. https://e3d7cd9c9fa0807ca5cbdfe99b425a8d.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html

We can create an object in the following ways:

  1. ClassName object = ClassName.class.newInstance();  

Or

  1. ClassName object = (ClassName) Class.forName(“fully qualified name of the class”).newInstance();  

In the above statement, forName() is a static method of Class class. It parses a parameter className of type String. It returns the object for the class with the fully qualified name. It loads the class but does not create any object. It throws ClassNotFoundException if the class cannot be loaded and LinkageError if the linkage fails.

To create the object, we use the newInstance() method of the Class class. It works only when we know the name of the class and the class has a public default constructor.

In the following program, we have creates a new object using the newInstance() method.

CreateObjectExample4.java

  1. public class CreateObjectExample4  
  2. {   
  3. void show()    
  4. {    
  5. System.out.println(“A new object created.”);    
  6. }    
  7. public static void main(String[] args)   
  8. {   
  9. try  
  10. {  
  11. //creating an instance of Class class  
  12. Class cls = Class.forName(“CreateObjectExample4”);   
  13. //creates an instance of the class using the newInstance() method  
  14. CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();   
  15. //invoking the show() method  
  16. obj.show();   
  17. }   
  18. catch (ClassNotFoundException e)   
  19. {   
  20. e.printStackTrace();   
  21. }   
  22. catch (InstantiationException e)   
  23. {   
  24. e.printStackTrace();   
  25. }   
  26. catch (IllegalAccessException e)   
  27. {   
  28. e.printStackTrace();   
  29. }   
  30. }   
  31. }  

Output:

A new object created.

Using newInstance() Method of Constructor class

It is similar to the newInstance() method of the Class class. It is known as a reflective way to create objects. The method is defined in the Constructor class which is the class of java.lang.reflect package. We can also call the parameterized constructor and private constructor by using the newInstance() method. It is widely preferred in comparison to newInstance() method of the Class class.

Syntax:

  1. public T newInstance(Object… initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException  

The method parses an array of Objects as an argument. The values of primitive types wrapped in a wrapper Object of the appropriate type. It returns a new object created by calling the constructor. It throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, ExceptionInInitializerError Exceptions.

We can create an object in the following way:

  1. Constructor<Employee> constructor = Employee.class.getConstructor();   
  2. Employee emp3 = constructor.newInstance();  

Let’s create a program that creates an object using the newInstance() method.

CreateObjectExample5.java

  1. import java.lang.reflect.*;   
  2. public class CreateObjectExample5  
  3. {   
  4. private String str;   
  5. CreateObjectExample5()   
  6. {   
  7. }   
  8. public void setName(String str)   
  9. {   
  10. this.str = str;   
  11. }   
  12. public static void main(String[] args)   
  13. {   
  14. try  
  15. {   
  16. Constructor<CreateObjectExample5> constructor = CreateObjectExample5.class.getDeclaredConstructor();   
  17. CreateObjectExample5 r = constructor.newInstance();   
  18. r.setName(“JavaTpoint”);   
  19. System.out.println(r.str);   
  20. }   
  21. catch (Exception e)   
  22. {   
  23. e.printStackTrace();   
  24. }   
  25. }   
  26. }  

Output:

JavaTpoint

Using Deserialization

In Java, serialization is the process of converting an object into a sequence of byte-stream. The reverse process (byte-stream to object) of serialization is called deserialization. The JVM creates a new object when we serialize or deserialize an object. It does not use constructor to create an object. While using deserialization, the Serializable interface (marker interface) must be implemented in the class.

How to Create Object in Java

Serialization: The writeObject() method of the ObjectOutputStream class is used to serialize an object. It sends the object to the output stream.

Syntax:

  1. public final void writeObject(object x) throws IOException  

Deserialization: The method readObject() of ObjectInputStream class is used to deserialize an object. It references objects out of a stream.

Syntax:

  1. public final Object readObject() throws IOException,ClassNotFoundException  

Note: Make the filed static or transient if we do not want to include a field as a part of the object. It will not include in the serialization process.

Let’s understand the serialization and deserialization through a program.

Employee.java

  1. import java.io.Serializable;    
  2. public class Employee implements Serializable  
  3. {    
  4. int empid;    
  5. String empname;    
  6. public Empoyee(int empid, String empname)   
  7. {    
  8. this.empid = empid;    
  9. this.empname = empname;    
  10. }    
  11. }  

We have created a class named Employee whose object is to be serialized and deserialized.

Serialization of Java Object:

In the following program, we have serialized an object of Employee class by using the writeObject() method of the ObjectOutputStream class. The state of the object is saved in the employee.txt file.

SerializationExample.java

  1. import java.io.*;    
  2. class SerializationExample   
  3. {    
  4. public static void main(String args[])  
  5. {    
  6. Try  
  7. {    
  8. //Creating the object    
  9. Employee emp = new Employee(198054,”Andrew”);    
  10. //Creates a stream and writes the object    
  11. FileOutputStream fout=new FileOutputStream(“employee.txt”);    
  12. ObjectOutputStream out=new ObjectOutputStream(employeeout);    
  13. out.writeObject(emp);    
  14. out.flush();    
  15. //closes the output stream    
  16. out.close();    
  17. System.out.println(“Successfully Created”);    
  18. }  
  19. catch(Exception e)  
  20. {  
  21. System.out.println(e);  
  22. }    
  23. }    
  24. }    

Output:

Successfully Created

Deserialization of Java Object:

In the following program, we going to deserialize an object that we have serialized in the above program.

DeserializationExample.java

  1. import java.io.*;    
  2. class DeserializationExample   
  3. {    
  4. public static void main(String args[])  
  5. {    
  6. try  
  7. {    
  8. //Creating a stream to read the object    
  9. ObjectInputStream in=new ObjectInputStream(new FileInputStream(“employee.txt”));    
  10. Employee e=(Employee)in.readObject();    
  11. //prints the data of the serialized object    
  12. System.out.println(e.empid+” “+e.empname);    
  13. //closing the input stream    
  14. in.close();    
  15. }  
  16. catch(Exception e)  
  17. {  
  18. System.out.println(e);  
  19. }    
  20. }    
  21. }    

Output:

198054 Andrew

In the above five methods, we have noticed that the new keyword and both newInstance() methods use the constructor to create objects, while the rest two methods do not use the constructor.

Conclusion

Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors).

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x