As a Java developer, you have probably used and created POJOs in some (or all) of your projects. A POJO is a class that encapsulates a set of data, without any additional behavior to manipulate its state. It usually includes constructors, accessors, mutators, and the overridden methods from the object class (hashCode(), equals(), and toString()). The accessors and mutators allow access and assignment to state variables. Additionally, the mutators might include code to check the range of values that are assigned to the instance state. The following is an example:
final class Emp { private String name; private int age; public Emp(String name, int age) { this.name = name; this.age = age; } // accessor methods - getName, getAge public String getName() { return name; } public int getAge() { return age; } // mutator methods - setName, setAge public void setName() { this.name = name; } public void setAge() { this.age = age; } public boolean equals(Object obj) { if (obj == null || (!(obj instanceof Emp))) return false; else { if ( ( ((Emp)obj).getName().equals(this.name) && ( ((Emp)obj).getAge() ) == this.age)) { return true; } else return false; } } public String toString() { return name + ":" + age; } public int hashCode() { // ..code } }
One scenario is using the Emp class to save employee data to your database. Here's an example:
interface EmpDAO { Emp read(); void write(Emp emp); List<Emp> getAllEmp(); }
Similarly, you can use the Emp class to be passed in a message, sent over the network, inserted into a JSON object, and more.
All of this looks good. Most importantly, it has been working fine since Java was introduced to developers. So, what is the problem?