English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

POJO vs Java Bean

We know that in Java, POJO stands for Plain Old Java Object. Java POJOs and Bean classes share some common features, as shown below-

  • Both classes must be public, that is, accessible to everyone.

  • The properties or variables defined in both classes must be private, that is, they cannot be accessed directly.

  • Both classes must have a default constructor, that is, a constructor without parameters.

  • Public getters and setters must exist in both classes to access variables/Properties.

The only difference between these two classes is that Java serializes the java Bean object to retain the state of the Bean class when needed. Therefore, the Java Bean class must implement the Serializable or Externalizable interface.

Therefore, it can be said that all JavaBeans are POJOs, but not all POJOs are JavaBeans.

Example of a Java Bean class.

public class Employee implements java.io.Serializable {
   private int id;
   private String name;
   public Employee(){}
   public void setId(int id){this.id=id;}
   public int getId(){return id;}
   public void setName(String name){this.name=name;}
   public String getName(){return name;}
}

Example of a POJO class.

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;
   }
}