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:
- all JavaBean properties must have public setter and getter methods (as appropriate);
- all JavaBean instance variables should be private.
- the JavaBean class must have a no-arg constructor
- the JavaBean class must implement either Serializable or Externalizable;
Advantages of Bean
- A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
- The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled. - A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets. - The configuration settings of a Bean can be saved in persistent storage and restored
at a later time. - A Bean may register to receive events from other objects and can generate events that
are sent to other objects.
Advantages of POJO
- 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
- 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.
- 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.
- 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.
- 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.