Pojo Class in Java: How to Create?
Introduction
The term Plain Old Java Objects, or POJO, refers to Java objects that do not have any restrictions (for example, no requirement to implement Serializable interfaces, special access modifiers, etc.). It is also known as a free object.
There is no need for a special classpath for the POJO class in Java. Java POJO classes have gained popularity due to their readability and reusability in programs. Because POJO classes have no strict naming conventions, they are easier to read and write.
Java programs can use it since it does not adhere to any specific framework. As POJOs are generally simple, there is no dependency on other libraries, interfaces, or annotations. It can therefore get used in multiple project types (web, desktop, console, etc.) without requiring packages or modules to be imported.
There are getter and setter methods on POJOs, which act as pure data structures. Getters and Setters are useful in retrieving and updating the value of variables outside of the encapsulating class. Setters update variables' values while getters read them.
While there are no restrictions to Java's POJO classes in many ways, some things should get avoided.
POJO class restrictions
- It is not acceptable to extend prespecified classes from POJO classes. For example:
// "Sample" does not qualify as a POJO as it extends "javax.servlet.http.HttpServlet" |
public class Sample extends javax.servlet.http.HttpServlet { … }
- There should be no predefined interfaces in POJO classes. For example:
// "Sample" does not qualify as a POJO class as it implements "javax.ejb.EntityBean" |
- There should be no predefined annotations in a POJO class. For example:
// "Sample" does not fall under the POJO category because it contains "@javax.persistence.Entity" |
How does POJO Class work?
A POJO class represents a piece of business logic. As part of an MVC architecture, the controller interacts with business logic, which in turn contacts POJOs to access the data.
The following is an explanation of how the POJO class works.
Properties of POJO class
The POJO class has the following properties:
- The POJO class must get declared as a public class.
- The public default constructor is mandatory.
- There may be arguments in the constructor.
- The values of all objects must be accessible by other Java programs through public Getters and Setters.
- In POJO Classes, objects can have any access modification, including private, public, or protected. All instance variables, however, should get declared as private for better security.
- In POJOs, classes shouldn't extend predefined classes.
- There should be no predefined interfaces implemented.
- There should be no annotations predefined for it.
Code Sample
Following is the sample code for implementing the POJO class in java.
package Jtp.PojoDemo; Output: Name: Sam Id: S001 Salary: 50000.0 |