Anis Rahman’s Post

🤔6 Ways to Create Objects in Java — and what actually matters in real projects When we start Java, we learn only one way to create objects: using new. But later we discover there are multiple ways — which gets confusing quickly. 1️⃣ Using the new keyword Student s = new Student(); This is the normal and most common way. Pros✅ · Simple and fast · Easy to understand · Compile-time safety Cons❌ · Creates tight coupling between classes › Industry usage: Used everywhere. This is the default way in day-to-day coding. 2️⃣Using Class.newInstance() Old reflection method. Pros✅ · Historical method Cons❌ · Deprecated since Java 9 · Should not be used anymore › Industry usage: Obsolete. 3️⃣Using Reflection (Constructor.newInstance()) Frameworks can create objects dynamically at runtime using reflection. Pros✅ · Can create objects dynamically · Useful when class name is not known beforehand Cons❌ · Slower than new · Complex and exception-heavy · Harder to debug › Industry usage: Used heavily inside frameworks like Spring and Hibernate, not in daily coding. 4️⃣ Using Deserialization Objects recreated from stored data. Pros✅ · Useful for caching and distributed systems · Helps in data transfer between systems Cons❌ · Security risks if misused · Rare in beginner-level projects › Industry usage: Used in backend infrastructure and large systems. 5️⃣ Using clone() Creates a copy of an existing object. Pros✅ · Fast copying of objects Cons❌ · Confusing (shallow vs deep copy) · Considered bad practice today › Industry usage: Rarely used now. 6️⃣Dependency Injection (DI) Frameworks (like Spring Boot) create objects and give them to your classes automatically. Example idea: Instead of creating objects manually, the framework injects them for you. Pros✅ · Loose coupling · Easier testing · Better architecture for big apps Cons❌ · Requires framework setup · Can feel confusing initially › Industry usage: This is the most used approach in modern backend development. 🚀 Final Reality Check Used daily: · new keyword · Dependency Injection (Spring Boot) Used internally by frameworks: · Reflection · Deserialization Avoid: · clone() · Class.newInstance() #Java #Programming #SpringBoot #BackendDevelopment #LearningJourney

  • graphical user interface

To view or add a comment, sign in

Explore content categories