🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
There are several ways to create objects in Java. In this article, we will discuss five different ways to create objects in Java. We will understand each method with an example and its output.
1. Using the new Keyword
This is the most common way to create an object. It involves calling the constructor of the class using the new keyword.
Example:
public class Car {
private String color;
private String model;
public Car(String color, String model) {
this.color = color;
this.model = model;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
public static void main(String[] args) {
Car myCar = new Car("Red", "Toyota Corolla");
myCar.displayInfo();
}
}
Output:
Car Model: Toyota Corolla, Color: Red
2. Using Class.forName()
This method is used for dynamic class loading. It can throw a ClassNotFoundException.
Example:
public class Car {
private String color;
private String model;
public Car() {
this.color = "Blue";
this.model = "Honda Civic";
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
public static void main(String[] args) {
try {
Car myCar = (Car) Class.forName("Car").newInstance();
myCar.displayInfo();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
Output:
Car Model: Honda Civic, Color: Blue
3. Using clone()
This method creates a new object by copying the existing object's data. It requires the class to implement the Cloneable interface.
Example:
public class Car implements Cloneable {
private String color;
private String model;
public Car(String color, String model) {
this.color = color;
this.model = model;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
try {
Car originalCar = new Car("Green", "BMW X5");
Car clonedCar = (Car) originalCar.clone();
clonedCar.displayInfo();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Output:
Car Model: BMW X5, Color: Green
4. Using Object Deserialization
This method creates an object from a serialized form (a byte stream). It requires the class to implement the Serializable interface.
Example:
import java.io.*;
public class Car implements Serializable {
private static final long serialVersionUID = 1L;
private String color;
private String model;
public Car(String color, String model) {
this.color = color;
this.model = model;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
public static void main(String[] args) {
try {
// Serialize the object
Car carToSerialize = new Car("Black", "Audi A4");
FileOutputStream fileOut = new FileOutputStream("car.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(carToSerialize);
out.close();
fileOut.close();
// Deserialize the object
FileInputStream fileIn = new FileInputStream("car.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Car deserializedCar = (Car) in.readObject();
in.close();
fileIn.close();
deserializedCar.displayInfo();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
Car Model: Audi A4, Color: Black
5. Using a Factory Method
A factory method is a static method that returns an instance of a class. It encapsulates the object creation process.
Example:
public class Car {
private String color;
private String model;
private Car(String color, String model) {
this.color = color;
this.model = model;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
public static class CarFactory {
public static Car createCar(String color, String model) {
return new Car(color, model);
}
}
public static void main(String[] args) {
Car myCar = Car.CarFactory.createCar("White", "Mercedes-Benz C-Class");
myCar.displayInfo();
}
}
Output:
Car Model: Mercedes-Benz C-Class, Color: White
Conclusion
These are five different ways to create objects in Java. Each method has its use cases and advantages, and understanding these methods is crucial for effective Java programming.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Very useful article, especially beginners should know all these techniques
ReplyDelete