What is a POJO?
POJO stands for Plain Old Java Object. It is a term used to describe a simple Java class that follows basic coding conventions and does not depend on any specific frameworks or external libraries.
In simple words, a POJO is just a normal Java object created to hold and manage data in a clean and straightforward way.
Key Features of a POJO
A typical POJO usually includes:
- Private variables (fields) to store data
- Public getter and setter methods to access and update those fields
- Optional methods for additional behavior (like toString())
It may also have:
- A no-argument constructor
- A parameterized constructor
Properties of a POJO
A class is considered a POJO if it does not:
- Extend any predefined class (e.g., HttpServlet, EntityBean, etc.)
- Implement any predefined interface (e.g., javax.ejb.EntityBean)
- Contain framework-specific annotations (e.g., @entity, @Component)
Example
public class Employee {
private int id;
private String name;
// Default constructor
public Employee() {}
// Parameterized constructor
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
// Getter
public int getId() {
return id;
}
// Setter
public void setId(int id) {
this.id = id;
}
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
}
What is a JavaBean?
A JavaBean is a special type of POJO that follows a set of strict rules (conventions). It is mainly used to encapsulate data and make it reusable across applications.
Every JavaBean is a POJO, but not every POJO is a JavaBean.
Rules for a JavaBean
- Must implement the Serializable interface.
- Must have a no-argument constructor.
- All fields must be private.
- Each property should have corresponding getter and setter methods.
- Fields must be accessed only through these methods (not directly).
This design provides encapsulation and controlled access to object properties.
Top comments (0)