Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jul 15, 2024
Medium

POJO Class in Java

Author Aashna Luthra
0 upvote
Table of contents
Master SQL for Data Analyst roles at Deloitte, EY, PWC, KPMG
16 Jul, 2024 @ 01:30 PM
Speaker
Anuj Dhoundiyal
Manager - Data analytics @

Java is both a platform and a programming language. Programming with Java is high-level, reliable, object-oriented, and secure. It helps develop mobile apps, web apps, games, etc. 

POJO in Java stands for Plain Old Java Object. It is a common object that is not subject to any special limitations. There is no unique classpath needed for the POJO file. It improves a Java program's ability to be read and reused.

Because of how simple they are to maintain, POJOs are now generally accepted. It is simple to read and write them. There is no naming scheme for properties and methods in a POJO class. It can be used by any Java program and is not dependent on any Java Framework.

A POJO class often has variables, along with associated Getters and Setters.

Example

public class Student {
    // Fields
    private int studentId;
    private String name;
    private int age;

    // Constructor
    public Student(int studentId, String name, int age) {
        this.studentId = studentId;
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    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;
    }

    // toString() method for object representation
    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Explanation:

  • This Java class, Student, is a POJO (Plain Old Java Object) class.
  • It represents a simple model for a student entity with attributes like studentId, name, and age.
  • The class has private fields to encapsulate its state, ensuring data integrity.
  • It has a constructor to initialize the Student object with values for its attributes.
  • Getters and setters methods are provided for accessing and modifying the private fields, following the JavaBeans convention.
  • The toString() method is overridden to provide a string representation of the Student object, which is helpful for debugging and logging purposes.

Properties of POJO Class

  • To allow other Java programs to access an object's values, all objects must have some public getters and setters.
  • POJO class should be public.
  • POJO classes shouldn't extend predefined classes.
  • There shouldn't be any predetermined annotations on it.
  • A public default constructor is a must.
  • It might contain the constructor for arguments.
  • The POJO class object can have any access modifiers, including private, public, and protected. But for increased project security, all instance variables should be private.
  • It shouldn't use predetermined interfaces.

Working of POJO Class

A POJO (Plain Old Java Object) class is a regular Java class that encapsulates data and provides methods to access and manipulate that data. Here's how a POJO class typically works:

  • Encapsulation: The POJO class encapsulates its state using private fields. These fields are accessed and modified only through getter and setter methods, ensuring data integrity and enabling control over how the data is accessed and modified.
  • Attributes: The POJO class defines attributes to represent the properties or characteristics of an entity. These attributes can be of various data types such as int, String, boolean, etc.
  • Constructor: The POJO class usually provides one or more constructors to initialize its object with values for its attributes. This allows creating instances of the class with specific initial values.
  • Getters and Setters: The class provides getter methods to retrieve the values of its attributes and setter methods to modify those values. These methods follow the JavaBeans convention, allowing easy integration with frameworks and tools that rely on this convention.
  • Behavior Methods: Besides getter and setter methods, a POJO class may contain other methods to perform operations related to the object's behavior. These methods can manipulate the object's state or perform additional actions based on its attributes.
  • Serialization Support: POJO classes are often designed to support serialization, which allows objects to be converted into a stream of bytes for storage or transmission and then reconstructed back into objects when needed.
working pojo

Using of POJO Class in Java Program

To access the objects from the POJO class, do the following steps: 

  • Create a POJO class objects
  • Use the set() method for setting the values
  • Use the get() method to get the values


Step 1: Create a package pojoExample in Eclipse IDE. In the package create a java Student class and add following code to it

public class Student {  
    private String name;  
    private String roll;  
    private int marks;  
}


Step 2: Go to the ‘Source’ tab in the tab menu and select the option ‘Generate Getters and Setters’. The following dialog box appears

getters setters

Step 3:Select All’ the fields and click on the Generate button. The following code will be generated.

package pojoExample;

public class Student {
    private String name;  
    private String roll;  
    private int marks;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRoll() {
		return roll;
	}
	public void setRoll(String roll) {
		this.roll = roll;
	}
	public int getMarks() {
		return marks;
	}
	public void setMarks(int marks) {
		this.marks = marks;
	}  
  
}

Step 4: Now in the same package create a Demo.java class file and add the following code to it:

package pojoExample;

public class Demo {
    public static void main(String[] args) {  
        
        // Create a Student class object  
         Student stu= new Student();
   
         // Using the set() method to set the values
         stu.setName("Ninja");  
         stu.setRoll("201");  
         stu.setMarks(64);  


         // Using the get() method to get the values
          System.out.println("Name: "+ stu.getName()); 
          System.out.println("Roll: " + stu.getRoll());  
          System.out.println("Marks: " +stu.getMarks());  
     }  
}
demo class

Step 5: Run the application. The following output is generated.

Output:

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Create JSON with Date Fields Using POJO in Java🗒️

Create POJO with Date Fields as Strings

For creating POJO class with date fields as strings, let’s use getters and setters to get and set the first name, last name, departure date and return date. 

package pojoExample;

public class Flight{
	private String firstName;
	private String lastName;
	private String departureDate;
	private String returnDate;

	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getDepartureDate() {
		return departureDate;
	}
	public void setDepartureDate(String departureDate) {
		this.departureDate = departureDate;
	}
	public String getReturnDate() {
		return returnDate;
	}
	public void setReturnDate(String returnDate) {
		this.returnDate = returnDate;
	}
}

Create JSON Using POJO in Java

To obtain the required date, we'll use the LocalDate class. LocalDate's default format is yyyy-MM-dd

With Default Format Used by LocalDate

The LocalDate class makes it simple to obtain past and future dates. Let’s understand with an example how to create JSON using POJO in Java:

package pojoExample;

import java.time.LocalDate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Example1 {

	public static void main(String[] args) throws JsonProcessingException {

		Flight obj = new Flight();
		obj.setFirstName("John");
		obj.setLastName("Smith");

		// yyyy-MM-dd is the default format 
		LocalDate currentDate = LocalDate.now();

		// Get 5 days from current date
		obj.setDepartureDate(currentDate.plusDays(5).toString());


		// Get 15 days from current date
		obj.setReturnDate(currentDate.plusDays(15).toString());

		// conversion- POJO to JSON
		ObjectMapper objMapper = new ObjectMapper();
		String str = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		System.out.println(str);

		// conversion- JSON to POJO
		Flight newObj = objMapper.readValue(str, Flight.class);
		System.out.println("Flight departure date: "+ newObj.getDepartureDate());
		System.out.println("Flight return date: "+ newObj.getReturnDate());

	}

}

 

Output:

output2

With a Custom Format of a Date

package pojoExample;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Example2 {

	public static void main(String[] args) throws JsonProcessingException {

		Flight obj= new Flight();
		obj.setFirstName("John");
		obj.setLastName("Smith");

		//yyyy-MM-dd is default format 
		LocalDate currentDate = LocalDate.now();

		// Get 5 days from current date
   		obj.setDepartureDate(currentDate.plusDays(5).format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")));
   		
		// Get 15 days from current date
		obj.setReturnDate(currentDate.plusDays(15).format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")));
		
		// conversion- POJO to JSON
		ObjectMapper objMapper = new ObjectMapper();
		String str = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(booking1);
		System.out.println(str);

		// conversion- JSON to POJO
		Flight newObj = objMapper.readValue(str, Flight.class);
		System.out.println("Flight departure date: "+ newObj.getDepartureDate());
		System.out.println("Flight return date: "+ newObj.getReturnDate());
	}
 
}

 

Output:

output3

With Timestamp

package pojoExample;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Example3{

	public static void main(String[] args) throws JsonProcessingException {

		Flight obj= new Flight();
		obj.setFirstName("John");
		obj.setLastName("Smith");

		//yyyy-MM-dd is default format 
		LocalDateTime currentDate = LocalDateTime.now();

		// Get 5 days from current date
		obj.setDepartureDate(currentDate.plusDays(5).format(DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss")));
		
		// Get 15 days from current date
		obj.setReturnDate(currentDate.plusDays(15).format(DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss")));

		// conversion- POJO to JSON
		ObjectMapper objMapper = new ObjectMapper();
		String str = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(booking1);
		System.out.println(str);

		// conversion- JSON to POJO
		Flight newObj = objMapper.readValue(str, Flight.class);
		System.out.println("Flight departure date: "+ newObj.getDepartureDate());
		System.out.println("Flight return date: "+ newObj.getReturnDate());
	}
}

 

Output:

output4

Java Bean Class

A Java Bean class is a type of POJO (Plain Old Java Object) class that adheres to specific conventions, making it suitable for use in Java applications, particularly in frameworks like JavaBeans. These conventions include having a no-argument constructor, providing getter and setter methods for accessing and modifying its properties, and implementing Serializable interface for supporting object serialization. Java Bean classes are often used for encapsulating data and behavior, providing a standardized way to create reusable and easily maintainable components in Java applications.

Example:

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

    public Person() {
        // Default constructor
    }

    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;
    }
}

In this example, the Person class is a Java Bean class with properties name and age, along with corresponding getter and setter methods. It follows the conventions required for Java Bean classes, such as having a no-argument constructor and providing accessor methods for its properties.

POJO vs Java Bean

POJO

Java Bean

Except for Java norms, there are no further constraints in POJO.It is a unique class of POJO files with additional constraints to Java conventions.
Compared to Bean, it offers less control over the fields.Bean offers complete protection on fields.
Any access modifier, public, private, and protected, may be applied to a field.Fields can only be accessed privately.
It is not required for POJO to have a no-arg constructor; it may or may not.There must be a no-arg constructor.
The Serializable interface can be implemented in the POJO file, but it is not mandatory.The Serializable interface needs to be implemented by the Bean class.
The class names can be used to access the POJO class.Only the getters and setters can be used to access the Bean class.
Using the POJO has no drawbacks.The use of the Bean has the drawback that the object state, which should be immutable, can be changed by the public setter and default constructor.

We hope you have learned everything about POJO in Java. 🙌

Must Read Array of Objects in Java

Frequently Asked Questions

Why we are using POJO in Java?

We use POJOs (Plain Old Java Objects) in Java for simplicity, maintainability, and interoperability. They encapsulate data and behavior without relying on frameworks, promoting clean code.

What is the advantage of POJO class?

The advantage lies in their simplicity, as they facilitate easier understanding, testing, and integration within Java applications. POJOs promote clean code and are easily maintainable, ensuring flexibility and interoperability.

Where is REST Assured used?

Rest Assured is used to validate REST APIs using the Java library. The Java library acts as a headless client to interact with Rest web services. It is based on the Rest assured library and can validate the server's HTTP responses.

What are the different dependencies required for REST Assured testing?

The various dependencies required for testing REST assured are: Rest assured, Rest Assured Common, Rest Assured All, testNG, and json-path.

Conclusion 

In this blog, we studied POJO Class in Java and looked at some of its properties. POJOs (Plain Old Java Objects) play a crucial role in Java development by promoting simplicity, maintainability, and interoperability. These classes encapsulate data and behavior without relying on frameworks, fostering clean code practices and facilitating easier understanding, testing, and integration within Java applications.

You can refer to similar articles for more information

  1. Let’s write first GET REST Assured Test
  2. Let’s write first PUT REST Assured Test
  3. Setup a Basic REST Assured Maven Project in Eclipse IDE
  4. REST Assured –RequestSpecification – How the request will look like
  5. Let’s Write First DELETE Request in REST Assured

 

Refer to our guided paths on Code360 to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Also, look at the interview experiences for placement preparations. 

Happy Learning Ninja!