Exploring Java Bean vs POJO

Exploring Java Bean vs POJO

As we know that in Java POJO refers to the Plain old Java object.POJO and Bean class in Java shares some common features which are as follows −

  • Both classes must be public, Which is accessible to all.

  • Properties or variables defined in both classes must be private meaning they can't be accessed directly.

  • Both classes must have a default constructor which is a no-argument constructor.

  • Public Getter and Setter must be present in both classes to access the variables/properties.

The only difference between both the classes is Java makes java bean objects serialized so that the state of a bean class could be preserved in case required. So due to this, a Java Bean class must either implement a Serializable or Externalizable interface.

Due to this, it is stated that all JavaBeans are POJOs but not all POJOs are JavaBeans.

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

POJO vs Java Bean

POJOJava Bean
It doesn’t have special restrictions other than those forced by the Java language.It is a special POJO that has some restrictions.
It doesn’t provide much control over members.It provides complete control over members.
It can implement a Serializable interface.It should implement the serializable interface.
Fields can be accessed by their names.Fields are accessed only by getters and setters.
Fields can have any visibility.Fields have only private visibility.
There may/may not be a no-arg constructor.It must have a no-arg constructor.
It is used when you don’t want to give restrictions on your members and give the user complete access to your entityIt is used when you want to provide users with your entity but only some part of your entity.