Classes & Objects
The foundation of Java OOP — how classes define blueprints and objects are instances, with constructors, fields, methods, and the this keyword.
Last reviewed: January 2025
🔍 What Is It?
Class
A class is a template that defines:
- →Fields (instance variables) — the data/state each object holds
- →Methods — the behavior/actions objects can perform
- →Constructors — special methods to initialize objects
- →Static members — shared across all instances (class-level, not instance-level)
Object
An object is a runtime instance of a class:
- →Has its own copy of instance fields
- →Shares methods with all other instances (methods are in the class, not each object)
- →Lives on the heap, referenced by a variable on the stack
Records (Java 16+)
Immutable data classes with auto-generated constructor, getters, equals, hashCode, toString:
record Point(int x, int y) {}Key Concepts:
- →
this— refers to the current object instance - →
static— belongs to the class, not instances - →
final— on a class: cannot be subclassed; on a field: cannot be reassigned; on a method: cannot be overridden - →Access modifiers:
private,package-private(default),protected,public
🎯 Why Do We Need It?
Classes and objects are the core of OOP. They solve:
- →Modeling real-world entities — Employee, Order, Product are natural classes
- →Encapsulation — bundle data and behavior together; hide implementation details
- →Reusability — define once, instantiate many times
- →Code organization — group related functionality into cohesive units
Without classes, you'd have scattered variables and functions with no clear ownership — like C procedural code. In enterprise Java, every entity (User, Order, Product), every service (OrderService, PaymentService), and every configuration (AppConfig) is a class.
🏗️ What Happens in Real Projects?
In a real Spring Boot enterprise project:
// Entity class (JPA)
@Entity
public class Order {
@Id @GeneratedValue
private Long id;
private String customerId;
private BigDecimal totalAmount;
private OrderStatus status;
// getters, setters, business methods
}
// Service class
@Service
public class OrderService {
private final OrderRepository repo;
public Order createOrder(CreateOrderRequest req) { ... }
}
// Value object (Record, Java 16+)
record CreateOrderRequest(String customerId, List<OrderItem> items) {}⚙️ How It Works
Object Creation:
- JVM allocates memory on the heap for the object
- All instance fields are initialized to defaults (0, null, false)
- Constructor runs, setting fields to specified values
- Reference to the object is returned to the caller
Constructor Chaining:
- →
this()calls another constructor in the same class - →
super()calls the parent class constructor (implicit first line if not specified)
Static vs Instance:
- →Static fields: one copy shared by all instances — stored in Metaspace
- →Instance fields: each object has its own copy — stored on Heap
- →Static methods: called on the class, cannot access instance fields
- →Instance methods: called on an object, can access both static and instance fields
Garbage Collection:
Objects become eligible for GC when no references point to them.
💻 Example
Building a Real Enterprise Class — A complete Employee class showing all key concepts in one place.
🤔 Common Confusions
❓ What is the difference between a class and an object?
A class is a blueprint/template defined in code. An object is a live instance created from that blueprint at runtime. Employee is a class. The specific employee "John Smith with ID 42" is an object. You can create thousands of Employee objects from one Employee class.
❓ What is the difference between static and instance members?
Static members belong to the class — there is one copy shared by all instances. Instance members belong to each object — every object has its own copy. Use static for utility methods, constants, and counters. Use instance fields for object-specific state (name, age, salary).
❓ When should I use a Record vs a regular class?
Use Record for immutable data carriers — DTOs, value objects, API request/response bodies, configuration data. Use regular classes when you need mutability, inheritance, or complex business logic. Records cannot extend other classes (they implicitly extend Record) but can implement interfaces.
🚨 Common Production Issues
Mutable objects shared across threads — if multiple threads access the same object and at least one modifies it, you have a race condition. Use immutable objects (records, final fields) or synchronization.
equals/hashCode not overridden — objects used in HashSet or as HashMap keys must have consistent equals and hashCode. Default Object.equals() compares references, not values.
Static mutable state — static fields shared across all instances cause bugs in multi-threaded environments and make testing hard. Prefer dependency injection over static state.
Constructors with too many parameters — more than 4-5 parameters is a code smell. Use Builder pattern or records with named fields.
✅ Best Practices
Always override equals() and hashCode() together, based on the same fields.
Make fields private and provide getters/setters only where needed.
Use records (Java 16+) for immutable data carriers — they eliminate boilerplate.
Prefer static factory methods over constructors for complex object creation.
Keep classes small and focused — Single Responsibility Principle.
Use final on fields that should not change after construction.
🏛️ Architect's Note
In modern Spring Boot applications, most classes fall into clear categories: @Entity (JPA data model), @Service (business logic), @Repository (data access), @Controller/@RestController (HTTP layer), and Records/DTOs (data transfer). This layered architecture with clear class responsibilities is what makes enterprise codebases maintainable. Avoid "god classes" that do everything.
💬 Frequently Asked Questions
🎯 Key Takeaways
🔗 Related Topics
🎯 Practice this topic in interviews
Core Java Interview Prep
Practice interview questions that connect directly to this technology track.
↗ Where this topic fits
Core Java Technology Guide
Return to the Core Java learning hub.
Backend Engineer Career Path
A structured journey through Core Java, Spring Boot, production backend engineering, and interview preparation.
Full Stack Java Developer Career Path
A guided route through frontend foundations, Java backend engineering, delivery workflows, and interview readiness.
Sources
Sources / References
Use these Core Java references to verify the concept in official docs and continue into the most relevant SplashRide pages.
Official documentation
Related SplashRide pages
SplashRide Core Java learning path
Browse the full Core Java topic collection and learning order on SplashRide.
Core Java Interview Prep
Practice Core Java interview questions and scenario-based answers.
Backend Engineer Career Path
A structured journey through Core Java, Spring Boot, production backend engineering, and interview preparation.
Full Stack Java Developer Career Path
A guided route through frontend foundations, Java backend engineering, delivery workflows, and interview readiness.
Encapsulation
How encapsulation protects object state, enforces invariants, and makes code maintainable — the OOP principle every senior developer relies on.
Inheritance
How Java inheritance works — extends, super, method overriding, and when to use inheritance vs composition in real enterprise projects.