POJO, Enum, Final & Records
POJO pattern, enumerations, final keyword, Java Records
- Build proper POJOs following Java conventions
- Master enum with methods, constructors, and fields
- Apply the final keyword to variables, methods, and classes
Series:
Java Core Concepts | Chapter: Types of Classes — Part 3 Audience: Beginner to Intermediate Java Developers Coverage: POJO Classes, Enum (normal, custom values, method override, abstract method, interface), Enum vs Static Final, Final Class
Table of Contents
- POJO Classes
- Enum — Introduction
- Enum — Properties & Rules
- Enum — Normal (Basic) Usage
- Enum — Built-in Methods
- Enum — Custom Values
- Enum — Method Override by Constant
- Enum — Abstract Methods
- Enum — Implementing an Interface
- Enum vs Static Final Constants
- Final Class
- Interview Question Bank
- Master Summary
Mind Map Chapter Overview
1. POJO Classes
What is a POJO?
POJO stands for Plain Old Java Object. The name itself tells the story — it is the simplest, most basic form of a Java class, with no fancy framework-specific features attached.
Definition
A POJO is a simple Java class that contains only fields (variables) and their getter and setter methods, with no special framework dependencies, annotations, inheritance, or interface implementations.
Rules What Makes a Class a POJO?
| Rule | Requirement |
|---|---|
| Class access modifier | Must be public |
| Constructor | Must have a public default (no-arg) constructor |
| Fields | Can be any access modifier (private, public, protected, default) |
| Getter/Setter methods | Must be present for each field |
| Annotations | ❌ No annotations (no @Entity, @Table, etc.) |
| Inheritance | ❌ Must NOT extend any class |
| Interface | ❌ Must NOT implement any interface |
Code Example A Valid POJO
1public class Student {2 // Fields — any access modifier allowed3 int defaultField;4 private String name;5 protected int age;6 public String city;7
8 // Getter and Setter for each field9 public String getName() {10 return name;11 }12
13 public void setName(String name) {14 this.name = name;15 }16
17 public int getAge() {18 return age;19 }20
21 public void setAge(int age) {22 this.age = age;23 }24
25 public String getCity() {26 return city;27 }28
29 public void setCity(String city) {30 this.city = city;31 }32
33 // Public default constructor (auto-provided by Java since no other constructor defined)34}POJO Checklist for This Class
| Check | Status |
|---|---|
Class is public | ✅ |
| Has public default constructor | ✅ (Java auto-generates) |
| Has variables | ✅ |
| Has getter/setter methods | ✅ |
No annotations (@Entity, @Table, etc.) | ✅ |
Does not extend any class | ✅ |
Does not implement any interface | ✅ |
What is NOT a POJO?
1// ❌ NOT a POJO — extends another class2public class Student extends Person { ... }3
4// ❌ NOT a POJO — implements an interface5public class Student implements Serializable { ... }6
7// ❌ NOT a POJO — has annotations (JPA/Spring annotations)8@Entity9@Table(name = "students")10public class Student {11 @Column12 private String name;13}Where Are POJOs Used in Real Projects?
Use Case 1 Request Object Mapping
When a client sends a request to your system, the incoming data should not be used directly across all your internal classes. A POJO acts as a mapper/transformer:
Why this pattern?
- If the request structure changes (e.g.,
id→customer_id), you only update the mapper — not every class - Internal classes work with your own well-named POJO, not raw external data
- Decouples your internal code from external API contracts
1// Request object from client2class RequestDto {3 int id;4 String name;5}6
7// Your internal POJO — insulated from external changes8public class CustomerPojo {9 int customerId;10 String customerName;11
12 public int getCustomerId() { return customerId; }13 public void setCustomerId(int id) { this.customerId = id; }14 public String getCustomerName() { return customerName; }15 public void setCustomerName(String name) { this.customerName = name; }16}17
18// Mapping layer — only ONE place to update if external structure changes19CustomerPojo map(RequestDto req) {20 CustomerPojo pojo = new CustomerPojo();21 pojo.setCustomerId(req.id);22 pojo.setCustomerName(req.name);23 return pojo;24}Use Case 2 Database Entity Layer
In a typical layered architecture (Controller → Service → Repository → DB), the repository layer uses entity classes that mirror the database table — these are effectively POJOs (before annotations are added):
1Client Request2 ↓3Controller (REST API)4 ↓5Service (Business Logic)6 ↓7Repository (DB access)8 ↓ ↑9 Database — StudentEntity POJO maps to student tablePOJO vs Related Concepts
| Concept | Relation to POJO |
|---|---|
| JavaBean | A stricter POJO — must be Serializable, fields must be private, getters/setters must follow naming convention exactly |
| DTO (Data Transfer Object) | A POJO used specifically to transfer data between layers |
| Entity | A POJO annotated with JPA annotations (@Entity, @Table) — technically no longer a pure POJO |
2. Enum Introduction
The Problem Before Enum
Before understanding enum, recall how we define constants in Java:
1public class WeekConstants {2 public static final int MONDAY = 0;3 public static final int TUESDAY = 1;4 public static final int WEDNESDAY = 2;5 public static final int THURSDAY = 3;6 public static final int FRIDAY = 4;7 public static final int SATURDAY = 5;8 public static final int SUNDAY = 6;9}This works, but has problems (discussed in depth in Section 10).
What is Enum?
An enum (enumeration) is a special Java class that represents a collection of constants. All constants in an enum are implicitlypublic static final.
1public enum Day {2 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY3}3. Enum Properties & Rules
Key Properties
| Property | Detail |
|---|---|
| Keyword | enum (replaces class) |
| Constants | All constants are public static final implicitly |
| Ordinal | Each constant gets an auto-assigned integer value starting from 0 |
| Extends | Implicitly extends java.lang.Enum (cannot extend any other class) |
| Implements | Can implement any number of interfaces |
| Constructor | Always private — even if you write default, bytecode makes it private |
| Instantiation | ❌ Cannot be instantiated with new (constructor is private) |
| Other classes extending enum | ❌ Not allowed |
| Variables | ✅ Can have variables |
| Methods | ✅ Can have methods (including static and abstract) |
| Abstract methods | ✅ Allowed — but ALL constants must implement them |
Why Can't Enum Extend Another Class?
Java does not allow a class to extend more than one class. Since every enum already implicitly extends java.lang.Enum, it cannot extend anything else. It can, however, implement multiple interfaces.
Why Is the Constructor Always Private?
1public enum EnumSample {2 MONDAY, TUESDAY3 // No constructor written...4}Even without writing a constructor, the compiler generates a private default constructor in the bytecode. This is why you cannot do:
1// EnumSample e = new EnumSample(); // ❌ Compile error — constructor is privateThe constants themselves (MONDAY, TUESDAY) are created internally by the enum class calling its own private constructor — this is the only valid way.
4. Enum Normal (Basic) Usage
Syntax
1public enum EnumSample {2 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;3}; at the end of the constants list is required when you add variables, constructors, or methods below. It is optional for simple enums but is good practice to always include it.Ordinal Values
Internally, Java assigns ordinal (index) values starting from 0:
| Constant | Ordinal |
|---|---|
| MONDAY | 0 |
| TUESDAY | 1 |
| WEDNESDAY | 2 |
| THURSDAY | 3 |
| FRIDAY | 4 |
| SATURDAY | 5 |
| SUNDAY | 6 |
5. Enum Built-in Methods
All enums inherit these static and instance methods from java.lang.Enum. You don't need to define them — they're automatically available.
The Four Most Important Methods
| Method | Type | What it does |
|---|---|---|
values() | Static | Returns an array of all constants in declaration order |
ordinal() | Instance | Returns the zero-based position of the constant |
valueOf(String name) | Static | Returns the enum constant whose name matches the given string |
name() | Instance | Returns the exact name of the constant as declared |
Code Example All Four Methods
1public enum EnumSample {2 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;3}4
5public class Main {6 public static void main(String[] args) {7
8 // 1. values() — iterate over all constants9 System.out.println("=== values() + ordinal() ===");10 for (EnumSample sample : EnumSample.values()) {11 System.out.println(sample + " → ordinal: " + sample.ordinal());12 }13
14 // 2. valueOf() — get enum object by name string15 System.out.println("\n=== valueOf() ===");16 EnumSample friday = EnumSample.valueOf("FRIDAY");17 System.out.println("Got: " + friday); // FRIDAY18
19 // 3. name() — get the declared name of the constant20 System.out.println("\n=== name() ===");21 System.out.println(friday.name()); // FRIDAY22 }23}=== values() + ordinal() === MONDAY → ordinal: 0 TUESDAY → ordinal: 1 WEDNESDAY → ordinal: 2 THURSDAY → ordinal: 3 FRIDAY → ordinal: 4 SATURDAY → ordinal: 5 SUNDAY → ordinal: 6 === valueOf() === Got: FRIDAY === name() === FRIDAY
Method Explanations
`values()`
Returns an array of all constants in their declaration order. Comes from java.lang.Enum. Use it when you need to iterate over all constants.
1EnumSample[] all = EnumSample.values();2// all = [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]`ordinal()`
Returns the zero-based index of the constant in the declaration order. Think of it as the default "position number" Java assigns automatically.
1EnumSample.MONDAY.ordinal() // 02EnumSample.FRIDAY.ordinal() // 43EnumSample.SUNDAY.ordinal() // 6`valueOf(String name)`
Looks up a constant by its exact name (case-sensitive). Returns the matching enum constant.
1EnumSample day = EnumSample.valueOf("FRIDAY"); // EnumSample.FRIDAY2// EnumSample.valueOf("friday"); // ❌ IllegalArgumentException — case-sensitive`name()`
Returns the exact string name of the constant as it was declared in the enum.
1EnumSample.FRIDAY.name() // "FRIDAY"name() and toString() return the same value by default, but toString() can be overridden while name() cannot. Use name() when you need the guaranteed, original declared name.6. Enum Custom Values
Overview
By default, each constant gets an ordinal (0, 1, 2...). But you can also attach custom values to each constant — like a descriptive number, a label, or any data you need.
How It Works
Each constant can call the enum's private constructor to pass custom values. You define:
- Member variables (fields) for the custom data
- A private parameterized constructor that sets those fields
- Getter methods to retrieve the values
1public enum EnumSample {2 MONDAY(101, "First day of the week"),3 TUESDAY(102, "Second day"),4 WEDNESDAY(103, "Third day"),5 THURSDAY(104, "Fourth day"),6 FRIDAY(105, "Fifth day"),7 SATURDAY(106, "Second week of"),8 SUNDAY(107, "Last day");9
10 // Member variables — one per constant11 private int val;12 private String comment;13
14 // Private parameterized constructor15 private EnumSample(int val, String comment) {16 this.val = val;17 this.comment = comment;18 }19
20 // Getters21 public int getVal() { return val; }22 public String getComment() { return comment; }23
24 // Static method — finds constant by custom int value25 public static EnumSample getEnumFromValue(int value) {26 for (EnumSample sample : EnumSample.values()) {27 if (sample.val == value) {28 return sample;29 }30 }31 return null;32 }33}Using Custom Values
1public class Main {2 public static void main(String[] args) {3 // Access custom value directly4 System.out.println(EnumSample.MONDAY.getVal()); // 1015 System.out.println(EnumSample.MONDAY.getComment()); // First day of the week6
7 // Find enum constant by its custom integer value8 EnumSample found = EnumSample.getEnumFromValue(107);9 System.out.println(found); // SUNDAY10 System.out.println(found.getComment()); // Last day11 }12}101 First day of the week SUNDAY Last day
Step-by-Step How Constants Call the Constructor
MONDAY, TUESDAY, etc.) are the only ones allowed to call the private constructor — they do so right in their declaration MONDAY(101, "First day of the week"). No external code can call new EnumSample(...).Key Rules for Custom Values
| Rule | Detail |
|---|---|
| Member variables | Define as many as needed (one per custom value type) |
| Constructor | Must be private; must match the values passed in the constant declarations |
| Getters | Define for each variable you want to expose |
| Class-level static methods | Methods that aren't per-constant must be static |
| After the semicolon | Variables, constructors, and methods go AFTER the constants list and semicolon |
7. Enum Method Override by Constant
Overview
Every method defined in the enum body is available to all constants. But individual constants can override that method to provide their own behavior.
Code Example
1public enum EnumSample {2 MONDAY {3 // MONDAY overrides the shared dummyMethod4 @Override5 public void dummyMethod() {6 System.out.println("Monday dummy method");7 }8 },9 TUESDAY,10 WEDNESDAY,11 THURSDAY,12 FRIDAY,13 SATURDAY,14 SUNDAY;15
16 // Default implementation — used by all constants that don't override17 public void dummyMethod() {18 System.out.println("Default dummy method");19 }20}21
22public class Main {23 public static void main(String[] args) {24 EnumSample.FRIDAY.dummyMethod(); // Default dummy method25 EnumSample.MONDAY.dummyMethod(); // Monday dummy method26 EnumSample.TUESDAY.dummyMethod(); // Default dummy method27 }28}Default dummy method Monday dummy method Default dummy method
How It Works
The method defined in the enum body is the default for all constants. When a constant opens a block { ... } before its comma, it can override any of these shared methods.
8. Enum Abstract Methods
Overview
An enum can declare an abstract method, which forces every single constant to provide its own implementation. This guarantees that no constant can be left without behavior.
Code Example
1public enum EnumSample {2 MONDAY {3 @Override4 public void dummyMethod() {5 System.out.println("In Monday");6 }7 },8 TUESDAY {9 @Override10 public void dummyMethod() {11 System.out.println("In Tuesday");12 }13 },14 SUNDAY {15 @Override16 public void dummyMethod() {17 System.out.println("In Sunday");18 }19 };20
21 // Abstract — all constants MUST implement this22 public abstract void dummyMethod();23}24
25public class Main {26 public static void main(String[] args) {27 EnumSample.MONDAY.dummyMethod(); // In Monday28 EnumSample.TUESDAY.dummyMethod(); // In Tuesday29 EnumSample.SUNDAY.dummyMethod(); // In Sunday30 }31}In Monday In Tuesday In Sunday
Abstract Method vs Default Method Override Comparison
| Aspect | Default Method + Override | Abstract Method |
|---|---|---|
| Constants must implement? | ❌ Optional (only override if needed) | ✅ Mandatory for ALL |
| Has shared default behavior? | ✅ Yes | ❌ No default |
| Use when | Most constants share behavior, some differ | Each constant MUST have its own logic |
9. Enum Implementing an Interface
Overview
An enum can implement one or more interfaces. The implementation applies to all constants — making it ideal for shared, common behavior.
Code Example
1interface MyInterface {2 String toLowerCase();3}4
5public enum EnumSample implements MyInterface {6 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;7
8 // Single implementation — shared by all constants9 @Override10 public String toLowerCase() {11 return this.name().toLowerCase();12 }13}14
15public class Main {16 public static void main(String[] args) {17 System.out.println(EnumSample.MONDAY.toLowerCase()); // monday18 System.out.println(EnumSample.FRIDAY.toLowerCase()); // friday19 System.out.println(EnumSample.SUNDAY.toLowerCase()); // sunday20 }21}monday friday sunday
How `this.name()` Works Here
Inside the interface implementation method, this refers to the current constant calling the method. So EnumSample.MONDAY.toLowerCase() → this = MONDAY → this.name() = "MONDAY" → .toLowerCase() = "monday".
Interface vs Abstract Method When to Use Which
| Approach | Use When |
|---|---|
| Interface | Behavior is common/shared across all constants; cleaner single implementation |
| Abstract method in enum | Each constant must have uniquely different behavior |
| Default method + selective override | Most constants share behavior, but a few need custom logic |
10. Enum vs Static Final Constants
The Core Question
If we can already create constants usingpublic static final, why do we need enum?
Side-by-Side Comparison
1// Approach 1 — Static Final Constants2public class WeekConstants {3 public static final int MONDAY = 0;4 public static final int TUESDAY = 1;5 public static final int WEDNESDAY = 2;6 public static final int THURSDAY = 3;7 public static final int FRIDAY = 4;8 public static final int SATURDAY = 5;9 public static final int SUNDAY = 6;10}11
12// Approach 2 — Enum13public enum Day {14 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;15}The Weekend Check Method Revealing the Differences
1// Using Static Final — int parameter2boolean isWeekend(int day) {3 if (WeekConstants.SATURDAY == day || WeekConstants.SUNDAY == day) {4 return true;5 }6 return false;7}8
9// Using Enum — Day parameter10boolean isWeekend(Day day) {11 if (Day.SATURDAY == day || Day.SUNDAY == day) {12 return true;13 }14 return false;15}Calling the Methods
1// Static Final version2isWeekend(2); // Returns false — what is 2? Programmer must know (Wednesday)3isWeekend(6); // Returns true (Sunday)4isWeekend(100); // Returns false — but 100 is not a valid day! No error, wrong behavior5
6// Enum version7isWeekend(Day.WEDNESDAY); // Returns false — readable, self-documenting8isWeekend(Day.SUNDAY); // Returns true9// isWeekend(100); // ❌ Compile error — 100 is not a Day enum valueAdvantages of Enum Over Static Final
| Advantage | Static Final | Enum |
|---|---|---|
| Type safety | ❌ Any integer accepted, even 100 or -1 | ✅ Only valid enum constants accepted |
| Readability | ❌ Code shows 6 — reader must know 6 = SUNDAY | ✅ Code shows Day.SUNDAY — self-documenting |
| Invalid value prevention | ❌ No compile-time check | ✅ Compile error if you pass an invalid value |
| Can carry extra data | ❌ Just a number | ✅ Can have multiple fields (val, comment, etc.) |
| Can have methods | ❌ No (it's just a field) | ✅ Yes — instance and static methods |
| Can implement interfaces | ❌ No | ✅ Yes |
| Iteration | ❌ Must maintain a separate array/list | ✅ values() built-in |
| Grouped in one place | ❌ Scattered in a utility class | ✅ Encapsulated in the enum itself |
Diagram Type Safety Advantage
11. Final Class
What is a Final Class?
A final class is a class declared with the final keyword that cannot be extended (subclassed) by any other class.
Definition
A final class prevents inheritance. No class can useextendsto inherit from afinalclass.
Syntax
1public final class TestClass {2 // class body3}Code Example
1public final class TestClass {2 void display() {3 System.out.println("I am a final class");4 }5}6
7// Attempting to extend TestClass8public class MyAnotherClass extends TestClass { // ❌ Compile error9 // Cannot inherit from final 'TestClass'10}Compile Error:
1Cannot inherit from final 'TestClass'Why Use a Final Class?
| Reason | Explanation |
|---|---|
| Immutability | Prevents subclasses from overriding methods and breaking expected behavior |
| Security | Ensures the class behavior cannot be altered by subclassing |
| Design intent | Communicates clearly: "This class is complete — not meant to be extended" |
Real-World Examples of Final Classes in Java
Java's standard library uses final classes extensively:
| Class | Why Final? |
|---|---|
java.lang.String | Immutability depends on no subclass overriding internal methods |
java.lang.Integer | Wrapper class must be reliable and unmodifiable |
java.lang.Math | Utility class — no point subclassing it |
`final` Keyword Three Contexts (Summary)
| Applied To | Meaning |
|---|---|
final variable | Value cannot be changed once assigned |
final method | Method cannot be overridden by subclass |
final class | Class cannot be extended/subclassed |
Diagram Final Class Restriction
12. Interview Question Bank
POJO
| Question | Key Answer |
|---|---|
| What is a POJO? | Plain Old Java Object — public class with fields, getters/setters, no annotations, no extends/implements, public default constructor |
| What is the difference between a POJO and a JavaBean? | JavaBean is stricter — must be Serializable, fields must be private, must follow exact getter/setter naming |
| Where are POJOs used in real projects? | Request object mapping layer and database entity layer |
| Can a POJO have a private field? | Yes — fields can have any access modifier |
Enum
| Question | Key Answer |
|---|---|
| What is an enum? | A class representing a collection of constants; all constants are implicitly public static final |
| Why can't an enum extend another class? | It implicitly extends java.lang.Enum — Java doesn't allow extending more than one class |
| Can an enum implement an interface? | Yes — any number of interfaces |
| Why is the enum constructor always private? | Prevents external instantiation; the compiler forces private even if you write default |
What is ordinal() in enum? | Returns the zero-based position of a constant in the declaration order |
What does values() return? | An array of all enum constants in declaration order |
What does valueOf(String) do? | Returns the enum constant whose name exactly matches the given string (case-sensitive) |
| Can an enum have abstract methods? | Yes — but ALL constants must implement the abstract method |
| Can individual constants override methods? | Yes — open a block { } before the constant's comma and override inside it |
| Can an enum have variables and custom constructors? | Yes — define fields and a private parameterized constructor; constants call it in their declarations |
Enum vs Static Final
| Question | Key Answer |
|---|---|
What are the advantages of enum over static final constants? | Type safety (invalid values caught at compile time), readability (self-documenting), can carry data, can have methods |
When would you still use static final over enum? | Very simple cases where a value can range freely (not restricted to a fixed set), e.g., a timeout duration |
Final Class
| Question | Key Answer |
|---|---|
| What is a final class? | A class that cannot be extended/subclassed |
| Can you instantiate a final class? | Yes — final only prevents inheritance, not instantiation |
| Give examples of final classes in Java | String, Integer, Math |
What's the difference between final variable, method, and class? | Variable: value fixed; Method: can't override; Class: can't extend |
13. Master Summary
Quick Revision Bullets
POJO:
- ✅ POJO = Plain Old Java Object — public class, variables + getters/setters, no annotations, no extends/implements
- ✅ Must have public default constructor (auto-generated if no constructor defined)
- ✅ Used at request mapping layer and entity/DB layer in real projects
- ✅ Decouples internal code from external API changes — only one mapping point needs updating
Enum:
- ✅
enumkeyword instead ofclass— represents a fixed set of constants - ✅ Constants are implicitly
public static final— you don't need to write it - ✅ Implicitly extends
java.lang.Enum→ cannot extend any other class; can implement interfaces - ✅ Constructor is always
private— evendefaultbecomesprivatein bytecode - ✅ Cannot instantiate enum with
newoutside the enum itself - ✅ Ordinals assigned automatically starting from
0 - ✅
values()= array of all constants |ordinal()= position |valueOf()= find by name |name()= constant's declared name - ✅ Custom values: define fields + private parameterized constructor; constants call it in their declaration
MONDAY(101, "First day") - ✅ Methods after the semicolon belong to each constant individually; mark
staticfor class-level behavior - ✅ Individual constants can override shared methods by opening a
{ }block - ✅ Abstract methods in enum → ALL constants must provide implementation
- ✅ Enum can implement interfaces → single implementation shared across all constants
Enum vs Static Final:
- ✅
static final int→ no type safety (any int accepted), poor readability (magic numbers) - ✅ Enum → type-safe (only valid constants accepted, compile error otherwise), self-documenting (
Day.SUNDAYvs6) - ✅ Enum can carry extra data, have methods, iterate via
values()—static finalcannot
Final Class:
- ✅
final class= cannot be extended/subclassed - ✅ You CAN instantiate a final class —
finalonly blocksextends, notnew - ✅ Examples:
String,Integer,Mathin Java's standard library - ✅
finalvariable = value fixed;finalmethod = can't override;finalclass = can't extend
End of Chapter — Java Classes Part 3: POJO, Enum & Final Class
Mastery check
How well can you recall this?
Finished this lesson?