Java is an object-oriented programming language, and object-oriented programming revolves around objects. Objects are the fundamental building blocks of Java programs, and they are instances of classes, which define their structure and behavior. In this blog, we’ll discuss how to create objects in Java, the different ways to do so, and best practices to follow.
What is Object and classes in Java?
In Java, a class is a blueprint or a template that defines the properties and behaviors of a set of objects. It is a user-defined data type that encapsulates data and methods. An object is an instance of a class. It is a runtime entity that represents a real-world entity or concept.
How many ways to create an object in Java?
There are five ways to create objects in Java:
a. Using the new keyword
In Java, the new keyword is used to create a new object of a class. The syntax for creating an object using the new keyword is as follows:
Here’s an example of using the new keyword to create an object of the Person class:
public class Main { private static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public void display() { System.out.println("Name: " + name + ", Age: " + age); } } public static void main(String[] args) { Person person = new Person("Ruhee", 26); person.display(); // Output: Name: Ruhee, Age: 26 } }
In this example, we define a Person class with two private instance variables name and age, and a constructor that takes these two variables as arguments and sets them. We also define a display() method that displays the name and age of the person.
In the Main class, we create a new object of the Person class using the new keyword and pass the name and age values to the constructor. We then call the display() method on the person object to display its details.
Output:
Name: Ruhee, Age: 26
Learn How to Compare Two Objects in Java, Here!
b. Using the Class.forName() method
public class Main { public static void main(String[] args) throws ClassNotFoundException { // get the Class instance using forName method Class obj = Class.forName("java.lang.Integer"); System.out.print("Class represented by obj: " + obj.toString()); } }
Output:
Class represented by obj: class java.lang.Integer
A complete guide to IIT Bombay Spoken Tutorial, here!
c. Using newInstance() method is a method of the Constructor class
In Java, the newInstance() method is a method of the Constructor class that creates a new instance of a class using its default constructor. This method is commonly used in reflection, which is a technique used to inspect and modify the behavior of code at runtime.
Here’s an example of how to use the newInstance() method to create an instance of a class:
The code you provided is mostly correct, but it’s missing the public keyword before the Main class declaration, which causes a compilation error. Here’s the corrected code:
// Java program to demonstrate Constructor.newInstance() method import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class newtum { public static void main(String... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // An array of constructor Constructor[] constructor = Test.class.getConstructors(); // Apply newInstance method Test sampleObject = (Test)constructor[0].newInstance(); System.out.println(sampleObject.value); } } class Test { String value; public Test() { System.out.println("New Instance is created "); value = "New Instance"; } }
Output:
When you run this code, it should print the following output:
New Instance is created
New Instance
Overall, the newInstance() method provides a powerful way to create instances of classes at runtime using their default constructors. However, its use should be limited to cases where reflection is necessary, as it can make the code more complex and harder to understand.
d. Using clone() method
You can create a copy of an existing object using the clone() method. Syntax: ClassName objectName = (ClassName) existingObjectName.clone();
// A Java program to demonstrate deep copy using clone() // An object reference of this class is contained by Test2 class Test { int obj1, obj2; } class Test2 implements Cloneable { int a, b; Test c = new Test(); public Object clone() throws CloneNotSupportedException { // Assign the shallow copy to Test2 t = (Test2)super.clone(); // Creating a deep copy for c t.c = new Test(); t.c.obj1 = c.obj1; t.c.obj2 = c.obj2; // Create a new object for the field c return t; } } public class Main { public static void main(String args[]) throws CloneNotSupportedException { Test2 t1 = new Test2(); t1.a = 10; t1.b = 20; t1.c.obj1 = 30; t1.c.obj2 = 40; Test2 t3 = (Test2)t1.clone(); t3.a = 100; // Change in primitive type of t2 will not be reflected in t1 field t3.c.obj1 = 300; // Change in object type field of t2 will not be reflected in t1(deep copy) System.out.println(t1.a + " " + t1.b + " " + t1.c.obj1 + " " + t1.c.obj2); System.out.println(t3.a + " " + t3.b + " " + t3.c.obj1 + " " + t3.c.obj2); } }
Output:
10 20 30 40
100 20 300 40
Get complete Java Programming Exercises and Solutions here!
e. Using deserialization
You can create an object by deserializing it from a stream. Syntax: ObjectInputStream inStream = new ObjectInputStream(inputStream); ClassName objectName = (ClassName) inStream.readObject();
import java.io.*; class Emp implements Serializable { private static final long serialversionUID = 129348938L; transient int a; static int b; String name; int age; // Default constructor public Emp(String name, int age, int a, int b) { this.name = name; this.age = age; this.a = a; this.b = b; } } public class SerialExample { public static void printdata(Emp object1) { System.out.println("name = " + object1.name); System.out.println("age = " + object1.age); System.out.println("a = " + object1.a); System.out.println("b = " + object1.b); } public static void main(String[] args) { Emp object = new Emp("ab", 20, 2, 1000); String filename = "shubham.txt"; object = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream (filename); ObjectInputStream in = new ObjectInputStream (file); // Method for deserialization of object object = (Emp)in.readObject(); in.close(); file.close(); System.out.println("Object has been deserialized\n" + "Data after Deserialization."); printdata(object); // System.out.println("z = " + object1.z); } catch (IOException ex) { System.out.println("IOException is caught"); } catch (ClassNotFoundException ex) { System.out.println("ClassNotFoundException" + " is caught"); } } }
Explanation of the code:
Using the Serializable interface, this Java code illustrates how to serialize and deserialize an object. Name, age, instance variables a and b, and the Serializable interface are all implemented by the Emp class. A is designated as transitory, meaning it won’t be serialized, while b is designated as static, meaning all instances of the class will share it. A new instance of the Emp class is created by the main() method, and it is serialized to a file called shubham.txt. The object is then made null, the file is deserialized back into it, and the printdata() method is used to print the data. Try-catch blocks are used to handle the IOException and the ClassNotFoundException.
Output:
Object has been deserialized
Data after Deserialization.
name = ab
age = 20
a = 0
b = 1000
Tips and tricks while creating an object in Java
Here are some best practices to follow when creating objects in Java:
a. Follow naming conventions – Use meaningful and descriptive names for classes and objects.
b. Use constructors effectively – Constructors are used to initialize the state of an object. Use constructors to set the initial values of instance variables.
c. Avoid using the clone() method – The clone() method is considered to be broken and should be avoided. Instead, use a copy constructor or a factory method to create copies of objects.
d. Use immutable objects – Immutable objects are objects whose state cannot be changed once they are created. Use immutable objects to avoid side effects and simplify code.
e. Use the Singleton design pattern carefully – The Singleton pattern restricts the creation of objects to one instance. Use it judiciously, as it can introduce a global state and make testing difficult.
f. Be mindful of memory usage – Creating too many objects can lead to memory issues. Use object pooling or flyweight patterns to reuse objects and optimize memory usage.
In this blog, we discussed how to create objects in Java and the different ways to do so. We also covered best practices to follow when creating objects in Java, such as following naming conventions, using constructors effectively, avoiding the clone() method, using immutable objects, and being mindful of memory usage. By following these best practices, you can write clean, efficient, and maintainable Java code.
We hope that our blog post on “Creating Objects in Java” will effectively guide and inform you about your coding-related queries. To keep enhancing your coding skills, do check out Newtum’s website and explore our online coding courses covering Java, HTML, PHP, and more.