POJO vs Java Beans
From GeeksforGeeks
POJO
POJO (Plain Old Java Object) is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath.
POJOs are used for increasing the readability and re-usability of a program. POJOs have gained the most acceptance because they are easy to write and understand. They were introduced in EJB 3.0 by Sun microsystems.
A POJO should not:
Extend prespecified classes, Ex:
public class GFG extends javax.servlet.http.HttpServlet { … }
is not a POJO class.Implement prespecified interfaces, Ex:
public class Bar implements javax.ejb.EntityBean { … }
is not a POJO class.Contain prespecified annotations, Ex:
@javax.persistence.Entity public class Baz { … }
is not a POJO class.
POJOs basically define an entity. Like in your program, if you want an Employee class, then you can create a POJO as follows:
public class Employee {
String name;
public String id;
private double salary;
public Employee(String name, String id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public Double getSalary() {
return salary;
}
}
As you can see, there is no restriction on access-modifiers of fields. They can be private, default, protected, or public. It is also not necessary to include any constructor in it.
Java Beans
Beans are special type of Pojos. There are some restrictions on POJO to be a bean.
JavaBeans is a proper subset of POJOs.
Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens.
Fields should be private. This is to provide complete control on fields.
Fields should have getters or setters or both.
A no-arg constructor should be there in a bean.
Fields are accessed only by constructor or getter setters.
public class Bean {
// private field
private Integer property;
// No-arg constructor
Bean() {
}
// getter method for property
public void setProperty(Integer property) {
if (property == 0) {
return;
}
this.property = property;
}
// setter method for property
public Integer getProperty() {
if (property == 0) {
return null;
}
return this.property;
}
}J
Last updated