top

Search

Java Tutorial

.

UpGrad

Java Tutorial

POJO Class in Java

Introduction

POJO improves the comprehensibility and re-usability of Java programs. The POJO files do not have any ties with the Java Frameworks. Hence, every Java Program can operate it. A POJO class in Java generally consists of variable values, getters, and setters. 

POJOs are free objects that help conduct data transfer, connect the components of a distributed operation model, improve communication between the layers of an application, and integrate variables in Java or encapsulation. A typical POJO class in Java example is to define the object values, like creating an Employee class in POJO that defines particular entities. 

The Controller in an MVC architecture communicates with the business logic, followed by interaction with the POJO class to access the data in Java. Accessing objects from a POJO class can be done by:

  • Creating objects in a POJO class

  • Setting the restrictions

  • Generating values using the get() method

A POJO class can be operated by accessing its name without necessarily implementing the Serializable interface since it has no mandatory standards. 

Overview

POJO (full form in Java: Plain Old Java Object) defines an object in Java that does not require a classpath. It has no bounds or special restrictions except the ones implemented by the Java Language Specification. POJOs are popular in programming because they are low maintenance and easy to read and write. 

This tutorial provides an uncomplicated guide on how to use POJO class in Java. It presents an exceptional and understandable narrative on the various concepts of the POJO class in Java.

Introduction to Plain Old Java Object (POJO)

To use a Plain Old Java Object, you must follow a few guidelines and a specific syntax. Let us first discuss the syntax.

  • Class Declaration

We first begin by declaring a class and giving it a meaningful name. Ensure that the class is public and follows the Java naming conventions (e.g., using CamelCase).

Example:

public class Person {
    // Class members and methods will be defined here
}
  • Private Fields

Private fields are used to encapsulate the data in the POJO. Use appropriate data types for each field (int for numbers and String for text).

Example:

public class Person {
    private String name;
    private int age;
    // Other fields...
}
  • Public Getters and Setters

Provide public getter and setter methods for each private field to allow access to the data. We must also follow the naming convention for getters and setters.

Example: 

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    // Other getters and setters...
}
  • Additional Methods (Optional)

We can add methods to perform specific operations or implement business logic in the POJO. These methods can be public or private based on their usage.

Example:

public class Person {
    private String name;
    private int age;

    // Constructors, getters, setters...

    public void celebrateBirthday() {
        age++;
        System.out.println("Happy birthday to " + name + "!");
    }
    // Other methods...
}

Using the POJO

To use the POJO, we must now create an instance of the class and access its methods and fields.

public class Main {
    public static void main(String[] args) {
        // Create an instance of the Person class
        Person person = new Person();


        // Set values using setters
        person.setName("John");
        person.setAge(30);


        // Access values using getters
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());


        // Call other methods
        person.celebrateBirthday();
    }
}

Now that we know how to use Plain Old Java Objects, here is a working program in Java:

(We must first make two separate files for the below program, a Person.java file and a Main.java file for the Person and Main classes.

(Person.java file)

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void celebrateBirthday() {
        age++;
        System.out.println("Happy birthday to " + name + "!");
    }
}

(Main.java file)

public class Main {
    public static void main(String[] args) {
        // Create an instance of the Person class
        Person person = new Person();


        // Set values using setters
        person.setName("Woobie");
        person.setAge(28);


        // Access values using getters
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

        // Call other methods
        person.celebrateBirthday();
    }
}

In the above program, the Person class represents the POJO with private fields (name and age), public getter and setter methods, and an additional method (celebrateBirthday()). The Main class contains the main method, which creates an instance of the Person class using the new keyword, sets values using setters, retrieves values using getters, and calls the celebrateBirthday() method.

History of POJO Class in Java

The term POJO was coined in 2000 by Martin Fowler, an America-based software developer. Since the introduction of Enterprise JavaBeans or EJB 3.0 (a well-designed server-side component system for business applications) by Sun Microsystem, Java has allowed access to the POJO class.

Properties of POJO Class 

Some key factors define POJO Class in Java, such as:

  • It must be public and always include a public default constructor.

  • Objects of the POJO class need to possess Getters and Setters to allow object value accessibility.

  • POJO Class in Java cannot extend a predefined class.

  • It might contain an argument constructor

  • It cannot own any prespecified annotation or use a predefined interface. 

POJO Restrictions and Best Practices

POJO class in Java does not require mandatory actions on naming the conventions, making it comparatively easier to work with while reading or writing file programs. Java framework does not bind the POJO operations, reducing its dependency on other annotations, interfaces and libraries. This makes POJO suitable for multiple web and desktop-based projects, generating a basic idea of when to use POJO class in Java.

If you are interested in learning how to get data from POJO class in Java, there are some key dos and dont’s to remember. 

Dos

  • POJOs must have a default constructor with public getter and setter methods

  • Exclude business logic, external dependencies, and annotations

Don'ts 

  • POJOs should not extend predefined classes 

  • A POJO class cannot implement a prespecified interface and annotations 

A POJO class is an object class in Java that can be used in a few steps. 

  • Create a POJO class in Java

  • Create an object in the class and instantiate it

  • Set values using the setter method

  • Retrieve the POJO class values using the getter method 

Example of POJO Class in Java

(Book.java file)

public class Book {
    private String title;
    private String author;
    private int publicationYear;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getPublicationYear() {
        return publicationYear;
    }

    public void setPublicationYear(int publicationYear) {
        this.publicationYear = publicationYear;
    }
}

In this example, we have a Book class as a POJO representing a book with title, author, and publication year as its properties.

The class has private fields title, author, and publicationYear, along with their corresponding getter and setter methods.

The getter methods allow you to retrieve the values of title, author, and publicationYear, while the setter methods allow you to set the values for these properties.

Using this Book class, you can create instances of books, set their title, author, and publication year using the setter methods, and retrieve these values using the getter methods.

(Main.java file)

public class Main {
    public static void main(String[] args) {
        // Create a book instance
        Book book = new Book();

        // Set book details
        book.setTitle("To Kill a Mockingbird");
        book.setAuthor("Harper Lee");
        book.setPublicationYear(1960);

        // Retrieve book details
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Publication Year: " + book.getPublicationYear());
    }
}

In the Main.java file, we create an instance of the Book class, set the book's title, author, and publication year using the setter methods, and retrieve these details using the getter methods.

Workings of the POJO Class

Here are the essentials of the POJO class:

  • Private Fields: A POJO class has private fields to encapsulate the data/state of an object. These fields are accessed through getter and setter methods.

  • Public Getter and Setter Methods: The getter methods provide access to the values of the private fields, while the setter methods allow modification of the field values. Getter and setter methods follow the naming convention getPropertyName() and setPropertyName(), respectively.

  • No-Argument Constructor: A POJO class often includes a no-argument constructor, initializing the object with default values. This constructor is important for frameworks that rely on object instantiation using reflection.

  • Parameterized Constructor: A POJO class may also have a parameterized constructor that accepts arguments to set the initial values of the object's fields. This constructor provides flexibility in object creation.

  • Serializable: A POJO class may sometimes implement the Serializable interface to support object serialization, allowing objects to be converted into a byte stream for storage or transmission.

  • No Business Logic: A POJO class typically does not contain complex business logic or behavior. It primarily focuses on representing the data/state of an object.

  • Encapsulation: The fields in a POJO class are often declared as ’private‘ to enforce encapsulation, ensuring that the object's internal state can only be accessed and modified through getter and setter methods.

  • Plain Java Class: A POJO class adheres to standard Java class conventions without any dependencies on specific frameworks or libraries. It is independent and can be used in various contexts.

JavaBeans

JavaBeans is a software component model for Java, which provides a set of conventions and guidelines for creating reusable and customizable components. JavaBeans are Java classes that follow specific naming conventions and design patterns to enable their integration into various development frameworks and tools.

POJO Vs. JavaBean

POJO and JavaBean are two different concepts in Java development. JavaBean is a particular type of POJO that follows a set of conventions and guidelines defined by the JavaBeans component model.

The main difference between a POJO and a JavaBean lies in the adherence to conventions and additional features provided by JavaBeans. POJOs are more general-purpose Java classes that focus on data encapsulation. At the same time, JavaBeans follow specific naming and design patterns to enable integration with frameworks and tools that rely on the JavaBeans component model.

POJO has no specific restrictions or requirements regarding naming conventions or interfaces. Meanwhile, JavaBean classes have specific naming conventions for properties, methods, and events, such as getXxx/setXxx for properties and addXxx/removeXxx for events.

Conclusion

The POJO class comprises the same members as in the database entity. Viewing through a Model View Controller architecture allows an interaction between the controller and the business logic, followed by contacting the POJO class in Java to access the object value. 

This tutorial provides a comprehensible insight into the concept of POJO classes in Java and explains its aspects. You can look for relevant courses on Java from upGrad to build up your expertise and improve your understanding of Java programs, especially if you are willing to excel in the POJO class in Java interview questions.

FAQs

1. What does a POJO class contain?

POJO class in Java generally consists of variables with getters and setters for the respective values. POJO classes can be visualized similarly to Beans since both help define objects that can improve the re-usability and readability of the files. 

2. What is the difference between entity class and POJO class?

There are no typical differences between a POJO class and an entity class. Adding annotations like @ENTITY to a POJO class can lead to considering that class as an Entity class. Hence, once you set the properties using the getter and setter method, every entity class is a POJO class. 

3. Can POJO have logic?

Yes, POJO can have business logic to fulfill its internal state and solve the communication needs with external sources like persisting data and interested parties.

Leave a Reply

Your email address will not be published. Required fields are marked *