Author Avatar

Pradeep Mishra

1

Share post:

POJO classes and Beans both are used to define java objects to increase their re-usability and readability. POJOs do not have other restrictions while beans are special POJOs with some restrictions. So let’s first discuss about POJO classes and then try to apply some restrictions on them to achieve Beans.

POJO

POJO refers to the Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification.They are simple to put in writing and perceive. They were introduced in EJB 3.0 by Sun Microsystems.

In Hibernate, POJO classes are used to store data and retrieve data.

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

The above example is a well-defined example of POJO class. As you can see, there is no restriction on access-modifier of fields. They can be private, default, protected or the public. It is also not necessary to include any constructor in it.

JavaBeans

A JavaBean is still a POJO but introduces a strict set of rules around how we implement it:

  • Access levels – properties are private and we expose getters and setters
  • Method names – getters and setters follow the getX and setX convention (in the case of a boolean, isX can be used for a getter)
  • Default Constructor – a no-argument constructor must be present so an instance can be created without providing arguments, for example during deserialization
  • Serializable – implementing the Serializable interface allows us to store the state
Example of Java Bean Class.
public class EmployeeBean implements Serializable {
 
    private static final long serialVersionUID = -3761445487636086334L;
    private String name;
    private LocalDate startDate;
 
    public EmployeeBean() {
    }
    public EmployeeBean(String name, LocalDate startDate) {
        this.name = name;
        this.startDate = startDate;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    //  additional getters/setters
}

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

I hope you have enjoyed this post and it helped you to understand the difference between JavaBeans and POJO classes. Please like and share and feel free to comment if you have any suggestions or feedback.

Golang gRPC communication made easy!
HTTP2 - Performance saviour for application

Discussion

Leave a Reply to JoãoCancel reply