Alessandro Lacava’s Blog

Google
 

August 21, 2006

POJO (Plain Old Java Object): The simpler…the better.

Filed under: Computer, Java — alessandrolacava @ 5:31 pm

A POJO is simply an object built using a Java class that does not implement any special interfaces such as those defined by the EJB 2 framework. An example of a POJO is a class composed by only:

  1. Properties, representing the object's state.
  2. Getter and setter methods for the properties.
  3. Business methods, representing behaviour.

Some properties can represent associations with other POJOs. Here is an example of implementation of the Person entity using a POJO:

JAVA:
  1. public class Person {
  2.  
  3. //1. properties
  4. private String firstName;
  5. private String secondName;
  6. private Address address;
  7.  
  8. //2. getters and setters
  9. public void setFirstName(String firstName)
  10. {
  11. this.firstName = firstName;
  12. }
  13. public String getFirstName()
  14. {
  15. return firstName;
  16. }
  17. [...]
  18.  
  19. //3. business methods
  20. public int computeAge()
  21. {
  22. //here the business logic to compute the person's age
  23. }
  24. }

As you can see the address property represents an association to another hypothetical POJO.

That's all! Code that handles database connections and so on shouldn't be contained within a POJO.

There are many advantages in using POJOs. First of all they're simple. Second they're very suitable to represent domain models. Many tools, like Hibernate, work best with domain models implemented using POJOs.