POJO Plain Old Java Object. Basically a class with attributes and its getters and setters.

public class User
{
 private String name;
 private int age;

 public void setName(String name){
    this.name = name;
 }

 public String getName(){
    return this.name;
 }

 //same for age

}

POJO vs Java Beans
A JavaBean is a Java object that satisfies certain programming conventions:

  1. all JavaBean properties must have public setter and getter methods (as appropriate);
  2. all JavaBean instance variables should be private.
  3. the JavaBean class must have a no-arg constructor
  4. the JavaBean class must implement either Serializable or Externalizable;

Advantages of Bean

  1. A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
  2. The properties, events, and methods of a Bean that are exposed to an application
    builder tool can be controlled.
  3. A Bean may be designed to operate correctly in different locales, which makes it
    useful in global markets.
  4. The configuration settings of a Bean can be saved in persistent storage and restored
    at a later time.
  5. A Bean may register to receive events from other objects and can generate events that
    are sent to other objects.

Advantages of POJO

  1. Getter & setter methods allow you to change the underlying data type without breaking the public interface of your class which makes it (and your application) more robust and resilient to changes
  2. You might want to call some other code such as raising a notification when the value is obtained or changed like in java bean. This is not possible with your current class.
  3. You can expose values that are not backed by a field I.E. calculated values such as getFullName() which is a concatenation of getFirstName() and getLastName() which are backed by fields.
  4. You can add validation to your setter methods to ensure that the values being passed are correct. This ensures that your class is always in a valid state.
  5. If the field is an object (I.E. not a primitive type) then the internal state of your class can be modified by other objects which can lead to bugs or security risks. You can protect against this scenario in your POJO’s getter by returning a copy of the object so that clients can work with the data without affecting the state of your object. Note that having a final field does not always protect you against this sort of attack as clients can still make changes to the object being referenced (providing that object is itself mutable) you just cannot point the field at a different reference once it has been set.

Comments are closed.