Example of JavaBean Class
Example 1:
Below is the implementation of the JavaBean Class:
JAVA
// Java Program of JavaBean class package geeks; public class Student implements java.io.Serializable { private int id; private String name; // Constructor public Student() {} // Setter for Id public void setId( int id) { this .id = id; } // Getter for Id public int getId() { return id; } // Setter for Name public void setName(String name) { this .name = name; } // Getter for Name public String getName() { return name; } } |
Example 2:
Below is the implementation of the JavaBean class:
JAVA
// Java program to access JavaBean class package geeks; // Driver Class public class Test { // main function public static void main(String args[]) { // object is created Student s = new Student(); // setting value to the object s.setName( "GFG" ); System.out.println(s.getName()); } } |
Output:
GFG
JavaBean class in Java
JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a Java class that should follow the following conventions:
- Must implement Serializable.
- It should have a public no-arg constructor.
- All properties in java bean must be private with public getters and setter methods.
Illustration of JavaBean Class
A simple example of JavaBean Class is mentioned below:
JAVA
// Java program to illustrate the // structure of JavaBean class public class TestBean { private String name; public void setName(String name) { this .name = name; } public String getName() { return name; } } |
Getter and Setter have important roles in the topic. So, let us check on Getter and Setter below: