POJO
A POJO (Plain Old Java Object) is a simple Java class used to model data without depending on any specific framework. It promotes clean, maintainable code and enhances portability and reusability across applications.
For ease of maintenance, POJOs are now widely recognized. They are easy to read and write. A POJO class does not have a naming convention for its properties and methods. It can be utilized by any Java application and is independent of any Java Framework.
Creating a POJO
A POJO class should follow these principles:
- No enforced inheritance: A POJO does not need to extend framework-specific base classes.
- Minimal implementation: A POJO avoids implementing framework-specific interfaces.
- No mandatory annotations: POJOs can have annotations but should not depend on framework-specific ones.
- No restrictions: A POJO class should not have any predefined restrictions on naming properties or methods.
Typically, a POJO contains:
- Private fields to store data
- Public getter and setter methods to access and modify the fields
- Optional constructors (default and/or parameterized)
- Optional override of methods like
toString()
,equals()
, andhashCode()
.
Example 1: Creating a Simple POJO Class for Student Data
This example demonstrates a simple POJO class to represent a student entity:
public class Student {// Step 1: Declare private fieldsprivate int id;private String name;private int age;// Step 2: Create a no-argument constructorpublic Student() {// Default constructor}// Step 3: Create a parameterized constructorpublic Student(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}// Step 4: Getter for idpublic int getId() {return id;}// Step 5: Setter for idpublic void setId(int id) {this.id = id;}// Step 6: Getter for namepublic String getName() {return name;}// Step 7: Setter for namepublic void setName(String name) {this.name = name;}// Step 8: Getter for agepublic int getAge() {return age;}// Step 9: Setter for agepublic void setAge(int age) {this.age = age;}// Optional: Override toString() method for better representation@Overridepublic String toString() {return "Student{id=" + id + ", name='" + name + "', age=" + age + "}";}}
In this example, a simple POJO has been created that:
- Has three private fields:
id
,name
, andage
- Provides both default and parameterized constructors
- Includes getter and setter methods for each field
- Overrides the
toString()
method for better object representation
Example 2: Employee POJO with Object Comparison
This example demonstrates a POJO with implementation of equals()
and hashCode()
methods for proper object comparison:
public class Employee {// Step 1: Declare private fieldsprivate int empId;private String name;private String department;private double salary;// Step 2: Create a no-argument constructorpublic Employee() {// Default constructor}// Step 3: Create a parameterized constructorpublic Employee(int empId, String name, String department, double salary) {this.empId = empId;this.name = name;this.department = department;this.salary = salary;}// Step 4: Getters and Setterspublic int getEmpId() {return empId;}public void setEmpId(int empId) {this.empId = empId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDepartment() {return department;}public void setDepartment(String department) {this.department = department;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}// Step 5: Override toString() method@Overridepublic String toString() {return "Employee{empId=" + empId +", name='" + name + "'" +", department='" + department + "'" +", salary=" + salary + "}";}// Step 6: Override equals() method for object comparison@Overridepublic boolean equals(Object obj) {if (this == obj) return true;if (obj == null || getClass() != obj.getClass()) return false;Employee employee = (Employee) obj;if (empId != employee.empId) return false;if (Double.compare(employee.salary, salary) != 0) return false;if (!name.equals(employee.name)) return false;return department.equals(employee.department);}// Step 7: Override hashCode() method for consistent hashing@Overridepublic int hashCode() {int result;long temp;result = empId;result = 31 * result + name.hashCode();result = 31 * result + department.hashCode();temp = Double.doubleToLongBits(salary);result = 31 * result + (int) (temp ^ (temp >>> 32));return result;}}
This POJO demonstrates:
- Implementation of proper object comparison with
equals()
andhashCode()
- A more complex data structure with multiple fields of different types
- Standard getter and setter methods following Java conventions
Best Practices
When working with POJOs in Java, consider these best practices:
- Encapsulation: Make fields private and provide public getter/setter methods to control access.
- Immutability: When possible, make POJOs immutable by removing setter methods and making fields final.
- Proper Constructors: Provide both a no-argument constructor (required by many frameworks) and parameterized constructors.
- Method Overrides: Override
toString()
,equals()
, andhashCode()
methods for better debugging and proper object comparison. - Serialization: Implement
Serializable
if the POJO needs to be transferred across networks or persisted. - Documentation: Include JavaDoc comments to describe the purpose of the POJO and its fields.
- Validation: Add validation in setter methods to ensure data integrity.
- Minimize Dependencies: Keep POJOs clean by avoiding dependencies on specific libraries or frameworks.
Frequently Asked Questions
1. What is the difference between POJO and JavaBean?
A POJO has no specific rules, while a JavaBean follows strict conventions: - JavaBeans must have a no-argument constructor - JavaBeans must implement Serializable - JavaBeans properties must have getter and setter methods - JavaBeans typically use private fields with public accessor methods
2. Can a POJO extend other classes or implement interfaces?
Yes, a POJO can extend other classes and implement interfaces. It becomes a POJO by virtue of not being dependent on any specific framework or having framework-specific code, not by its inheritance hierarchy.
3. What is the difference between POJO and JSON?
POJO is a simple Java object used to represent data in code, while JSON is a text-based format used to store and exchange data. POJOs exist in Java programs; JSON is used for communication between systems.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours