The Wayback Machine - https://web.archive.org/web/20240907182939/https://www.geeksforgeeks.org/pojo-vs-java-beans/
Open In App

POJO vs Java Beans

Last Updated : 01 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath. POJOs are used for increasing the readability and re-usability of a program. POJOs have gained the most acceptance because they are easy to write and understand. They were introduced in EJB 3.0 by Sun Microsystems.

Properties of POJO

  1. Extend prespecified classes, Ex: public class GFG extends javax.servlet.http.HttpServlet { … } is not a POJO class.
  2. Implement prespecified interfaces, Ex: public class Bar implements javax.ejb.EntityBean { … } is not a POJO class.
  3. Contain prespecified annotations, Ex: @javax.persistence.Entity public class Baz { … } is not a POJO class.

POJOs basically define an entity. Like in your program, if you want an Employee class, then you can create a POJO as follows:

Java




// Employee POJO class to represent entity Employee
public class Employee
{
    // default field
    String name;
 
    // public field
    public String id;
 
    // private salary
    private double salary;
 
    //arg-constructor to initialize fields
    public Employee(String name, String id,
                             double salary)
    {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
 
    // getter method for name
    public String getName()
    {
        return name;
    }
 
    // getter method for id
    public String getId()
    {
        return id;
    }
 
    // getter method for salary
    public Double getSalary()
    {
        return salary;
    }
}


Explaination of the above program:

The above example is a well-defined example of the POJO class. As you can see, there is no restriction on access-modifiers of fields. They can be private, default, protected, or public. It is also not necessary to include any constructor in it.
POJO is an object which encapsulates Business Logic. The following image shows a working example of the POJO class. Controllers interact with your business logic which in turn interact with POJO to access the database. In this example, a database entity is represented by POJO. This POJO has the same members as the database entity.

Java_bean

Java Beans

Beans are special type of Pojos. There are some restrictions on POJO to be a bean.

  1. All JavaBeans are POJOs but not all POJOs are JavaBeans.
  2. Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens.
  3. Fields should be private. This is to provide complete control on fields.
  4. Fields should have getters or setters or both.
  5. A no-arg constructor should be there in a bean.
  6. Fields are accessed only by constructor or getter setters.

Getters and Setters have some special names depending on field name. For example, if field name is someProperty then its getter preferably will be:

public "returnType" getSomeProperty()
{
return someProperty;
}

and setter will be

public void setSomePRoperty(someProperty)
{
this.someProperty=someProperty;
}

Visibility of getters and setters is generally public. Getters and setters provide the complete restriction on fields. e.g. consider below the property,

Integer age;

If you set visibility of age to the public, then any object can use this. Suppose you want that age can’t be 0. In that case, you can’t have control. Any object can set it 0. But by using the setter method, you have control. You can have a condition in your setter method. Similarly, for the getter method if you want that if your age is 0 then it should return null, you can achieve this by using the getter method.

Below is the implementation of the above topic:

Java




// Java program to illustrate JavaBeans
class Bean implements Serializable {
    // private field property
    private Integer property;
    public Bean()
    {
        // No-arg constructor
    }
 
    // setter method for property
    public void setProperty(Integer property)
    {
        if (property == 0) {
            // if property is 0 return
            return;
        }
        this.property = property;
    }
 
    // getter method for property
    public Integer getProperty()
    {
        if (property == 0) {
            // if property is 0 return null
            return null;
        }
        return property;
    }
}
 
// Class to test above bean
public class GFG {
    public static void main(String[] args)
    {
        Bean bean = new Bean();
 
        bean.setProperty(0);
        System.out.println("After setting to 0: "
                           + bean.getProperty());
 
        bean.setProperty(5);
        System.out.println("After setting to valid"
                           + " value: "
                           + bean.getProperty());
    }
}


Output:

After setting to 0: null
After setting to valid value: 5

POJO vs Java Bean

POJO

Java Bean

It doesn’t have special restrictions other than those forced by Java language. It is a special POJO which have some restrictions.
It doesn’t provide much control on members. It provides complete control on members.
It can implement Serializable interface. It should implement serializable interface.
Fields can be accessed by their names. Fields are accessed only by getters and setters.
Fields can have any visibility. Fields have only private visibility.
There may/may-not be a no-arg constructor. It must have a no-arg constructor.
It is used when you don’t want to give restriction on your members and give user complete access of your entity It is used when you want to provide user your entity but only some part of your entity.

Conclusion

POJO classes and Beans both are used to define java objects to increase their readability and reusability. POJOs don’t have other restrictions while beans are special POJOs with some restrictions.
 



Similar Reads

Implementing Message Queuing Technique in Netbeans Through Enterprise Java Beans
A Message Queues, allow one or more processes to write a message to be read by other processes. A message queue is implemented as a linked list of messages and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system. Procedure steps for Impleme
5 min read
Puzzle | The Pot of Beans
A pot contains 75 white beans and 150 black ones. Next to the pot is a large pile of black beans. A somewhat demented cook removes the beans from the pot, one at a time, according to the following strange rule: He removes two beans from the pot at random. If atleast one of the beans is black, he places it on the bean pile and drops the other bean,
1 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.net.Authenticator class in Java
Authenticator class is used in those cases where an authentication is required to visit some URL. Once it is known that authentication is required, it prompts the user for the same or uses some hard-coded username and password. To use this class, following steps are followed- Create a class that extends the Authenticator. Lets name it customAuth.Ov
3 min read
Java lang.Long.builtcount() method in Java with Examples
java.lang.Long.bitCount() is a built in function in Java that returns the number of set bits in a binary representation of a number. It accepts a single mandatory parameter number whose number of set bits is returned. Syntax: public static long bitCount(long num) Parameters: num - the number passed Returns: the number of set bits in the binary repr
3 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Java.util.zip.DeflaterOutputStream class in Java
Java.util.zip.DeflaterInputStream class in Java This class implements an output stream filter for compressing data in the "deflate" compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream. Constructors and Description DeflaterOutputStream(OutputStream out) : Creates a new output stream with
3 min read
Java.io.ObjectOutputStream Class in Java | Set 2
Java.io.ObjectOutputStream Class in Java | Set 1 More Methods: void write(byte[] buf) : Writes an array of bytes. This method will block until the byte is actually written. Syntax :public void write(byte[] buf) throws IOException Parameters: buf - the data to be written Throws: IOException void write(byte[] buf, int off, int len) : Writes a sub arr
8 min read
Java.lang.Boolean Class in Java
Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolea
8 min read
Java.Lang.Float class in Java
Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of the Float class can hold a single float value. There are mainly two constructors to initialize a Float object- Float(float b): Creates a Float o
6 min read
Java.Lang.Short class in Java
Short class is a wrapper class for the primitive type short which contains several methods to effectively deal with a short value like converting it to a string representation, and vice-versa. An object of Short class can hold a single short value. There are mainly two constructors to initialize a Short object- Short(short b): Creates a Short objec
6 min read
Java.lang.Integer class in Java
Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa. An object of the Integer class can hold a single int value. Constructors: Integer(int b): Creates an Integer object initialized with the value provided.Syntax
15 min read
Java.lang.Enum Class in Java
Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create obje
8 min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Java.net.NetworkInterface class in Java
This class represents network interface, both software as well as hardware, its name, list of IP addresses assigned to it, and all related information. It can be used in cases when we want to specifically use a particular interface for transmitting our packet on a system with multiple NICs. What is a Network Interface? A network interface can be th
6 min read
Java.net.Inet4Address class in Java
This class extends the InetAddress class and represents an IPv4 address. It provides methods to interpret and display useful information about IP addresses. Methods of this class take input in 4 formats: d.d.d.d: When this format is used as input, each of the given values are assigned to 4 bytes of the IP address from left to right.d.d.d: When this
3 min read
Java.net.Inet6Address class in Java
This class represents IPv6 address and extends the InetAddress class. Methods of this class provide facility to represent and interpret IPv6 addresses. Methods of this class takes input in the following formats: x:x:x:x:x:x:x:x -This is the general form of IPv6 address where each x can be replaced with a 16 bit hexadecimal value of the address. Not
5 min read
Java.net.InetSocketAddress class in Java
This class implements IP socket address( combination of IP address and port number). The objects of this class are immutable and can be used for binding, connecting purposes. Constructors : 1. InetSocketAddress(InetAddress addr, int port) : This constructor is similar to the general structure of a socket address with the attributes for Inet address
4 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.Collections.frequency() in Java with Examples
java.util.Collections.frequency() method is present in java.util.Collections class. It is used to get the frequency of a element present in the specified list of Collection. More formally, it returns the number of elements e in the collection. Syntax public static int frequency(Collection<?> c, Object o) Parameters : c - the collection in whi
2 min read
Java.util.concurrent.Semaphore Class in Java
A semaphore controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. What the counter is counting are permits that allow access to the shared resource. Thus, to access the resource, a thread must be granted a permit from the semaphore. Synta
6 min read
Java.net.URI class in Java
This class provides methods for creating URI instances from its components or by parsing the string form of those components, for accessing and retrieving different components of a URI instance. What is URI? URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular
11 min read
Java.net.DatagramSocket class in Java
Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java's mechanism for providing network communication via UDP inst
9 min read
Java.net.DatagramPacket class in Java
This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the message will be delivered or not, and they may also arri
5 min read
Java.net.MulticastSocket class in Java
This class is used for sending and receiving multicast IP packets. It extends DatagramSocket class and provides additional functionality for joining groups. A message sent to the group IP address will be received by all the clients who have joined the group. This must be kept in mind that for sending packets to the group, datagram socket doesn't ha
6 min read
Java.net.URLEncoder class in Java
This class is a utility class for HTML form encoding. Encoding makes the form of URL more reliable and secure. When the user request is triggered by a get method, the form parameters and their values are appended at the end of URL after a '?' sign. The problem arises when special characters are used for their values. In general case, HTML handles t
3 min read
Java.net.URLDecoder class in Java
This is a utility class for HTML form decoding. It just performs the reverse of what URLEncoder class do, i.e. given an encoded string, it decodes it using the scheme specified. Generally when accessing the contents of request using getParameter() method in servlet programming, the values are automatically decoded before they are returned. But some
2 min read
Java.util.PropertyPermission class in Java
This class is for property permission. It extends BasicPermission. The name is the name of the property ("java.home", "os.name", etc). The naming convention follows the hierarchical property naming convention. Also, an asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "java.*" or "*
4 min read
Article Tags :
Practice Tags :