Java Beans Vs POJO : Difference Between Java Beans And POJO

Posted By : Balgovind Prajapati | 25-Aug-2019

      POJO refers to Plain Old Java Object. It is an ordinary Java object. 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. These were introduced in EJB 3.0 by Sun microsystems.POJOs basically defines an entity.

      JavaBeans are practical classes, that are written in Java programming language. Beans are used to encapsulate objects into a single bean so that these can be passed as a single bean. Whenever we use Java Bean as , It must obey certain conventions about method naming, constructor and behavior. These conventions make it possible to have tools that can use, reuse, replace and connect Beans.

A POJO should not:

  1. Extend any other classes, Ex: public class Employee extends Runnable 
  2. Implement any other interfaces, Ex: public class Company implements Thread 
  3. Contain any other annotations, Ex: @RequestMapping public class City
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;
   }
}

 Beans are similar to POJO but there are some differences:  

  1. A Bean is POJO but POJO is not Bean.                
  2. A Bean always implements a Serializable interface.
  3. A Bean has not any argument constructor.
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;
   }  
} 

Conclusion:

  1. Both classes must be public.
  2. Properties or variables defined in both classes must be private i.e. can't be accessed directly.
  3. Both classes must have default constructor i.e no-argument constructor.
  4. Public Getter and Setter must be present in both the classes in order to access the variables/properties
  5. The only difference is Bean classes implements Serializable interface.

About Author

Author Image
Balgovind Prajapati

BalGovind is a Java Developer . He has good skill in Java, Spring, Hibernate, J2EE, MySql. He is a goal oriented and focused person.

Request for Proposal

Name is required

Comment is required

Sending message..