POJO vs Java Beans


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 i.e accessible to all.

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

  • Both classes must have default constructor i.e no argument constructor.

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

The only difference between both the classes is Java make java beans 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 implements 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;
   }
}

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements