POJO Class in Java – Definition, Syntax, and Example

POJO Class in Java - Definition, Syntax, Examples, FAQ & Related Links

4. POJO Class (Plain Old Java Object)

Definition

A POJO (Plain Old Java Object) is a simple Java class that follows a few basic rules and is mainly used to represent data. It does not follow any special Java model or framework conventions. POJOs make code easier to read, maintain, and test.

Characteristics of a POJO Class

  • Private fields – Data members should be private.
  • Public getters and setters – Used to access and modify the fields.
  • No-argument constructor – Usually included for flexibility.
  • No extends or implements – Should not extend predefined classes or implement unnecessary interfaces (unless needed for business logic).
  • Serializable (optional) – Can implement Serializable for object persistence.

Syntax of a POJO Class

public class Student {
    private String name;
    private int age;
    // No-argument constructor
    public Student() {}
    // Parameterized constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // Getter method for name
    public String getName() {
        return name;
    }
    // Setter method for name
    public void setName(String name) {
        this.name = name;
    }
    // Getter method for age
    public int getAge() {
        return age;
    }
    // Setter method for age
    public void setAge(int age) {
        this.age = age;
    }
}

Example

public class Main {
    public static void main(String[] args) {
        // Creating POJO object using parameterized constructor
        Student student = new Student("Rahul", 21);
        // Displaying initial values
        System.out.println("Name: " + student.getName());
        System.out.println("Age: " + student.getAge());
        // Modifying values using setter
        student.setName("Amit");
        student.setAge(22);
        // Displaying updated values
        System.out.println("Updated Name: " + student.getName());
        System.out.println("Updated Age: " + student.getAge());
    }
}

Frequently Asked Questions (FAQ)

Q1: What does POJO stand for?

A: POJO stands for Plain Old Java Object. It is a simple Java class used to represent data.

Q2: Can a POJO class extend other classes or implement interfaces?

A: Typically, POJOs do not extend predefined classes or implement interfaces unless required for business logic.

Q3: Why use POJOs?

A: POJOs make code easy to read, maintain, and test by keeping Java objects simple and free from framework dependencies.

Q4: Is it mandatory for a POJO to implement Serializable?

A: No, implementing Serializable is optional and is done if object persistence or network transfer is required.

Comments

Popular posts from this blog

Introduction to Java

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Top AI Tools for Social Media Marketing in 2025 – Automate & Grow Your Brand