A class can have many instances when you create multiple objects from it. This happens often in Spring services, repositories, controllers, or any object-oriented Java application.
Imagine a User
class that represents users in an application.
java
CopyEdit
public class User {
private final Logger LOGGER = LoggerFactory.getLogger(User.class); // ❌ Each User object gets its own Logger
private String name;
public User(String name) {
this.name = name;
LOGGER.info("User {} has been created", name);
}
}
📌 Problem:
User
object, a new Logger object is also created.User
objects log the same way.java
CopyEdit
public class UserApp {
public static void main(String[] args) {
User user1 = new User("Alice");
User user2 = new User("Bob");
User user3 = new User("Charlie");
}
}
📌 Output (3 separate Logger objects, unnecessary overhead):
pgsql
CopyEdit
INFO: User Alice has been created
INFO: User Bob has been created
INFO: User Charlie has been created
🔴 Each User
instance has its own Logger
, which is inefficient.
java
CopyEdit
public class User {
private static final Logger LOGGER = LoggerFactory.getLogger(User.class); // ✅ Shared across all User objects
private String name;
public User(String name) {
this.name = name;
LOGGER.info("User {} has been created", name);
}
}
🚀 Now, no matter how many User
instances you create, only one Logger
is used!