Normal Class: A Java class that is normally create.
Java Beans:
- All properties private (use getters/setters).
- A public no-argument constructor.
- Implements Serializable.
- Java Beans are reusable software components for Java.
- They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects.
- Output:-
// Java program to illustrate JavaBeansclass Bean{// private field propertyprivate Integer property;Bean(){// No-arg constructor}// setter method for propertypublic void setProperty(Integer property){if (property == 0){// if property is 0 returnreturn;}this.property=property;}// getter method for propertypublic int getProperty(){if (property == 0){// if property is 0 return nullreturn null;}return property;}}// Class to test above beanpublic 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());}}
After setting to 0: null After setting to valid value: 5
Pojo: Plain Old Java Object is a Java object not bound by any restriction .
- Example of Pojo :
// Person POJO class to represent entityPersonpublicclassPerson{// default fieldString name;// public fieldpublicString id;// private salaryprivatedoublesalary;//arg-constructor to initialize fieldspublicperson(String name, String id,doublesalary){this.name = name;this.id = id;this.salary = salary;}// getter method for namepublicString getName(){returnname;}// getter method for idpublicString getId(){returnid;}// getter method for salarypublicDouble getSalary(){returnsalary;}}Comparison between Java Bean Vs Pojo?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 visiblity. Fields have only private visiblity. There can 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.

No comments:
Post a Comment