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 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:
Setter and Getter Methods in Java
Setter and Getter Methods in Java properties are mentioned below:
Properties for setter methods:
- It should be public in nature.
- The return type a should be void.
- The setter method should be prefixed with the set.
- It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
- It should be public in nature.
- The return type should not be void i.e. according to our requirement, return type we have to give the return type.
- The getter method should be prefixed with get.
- It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use “is”.
// Java program to illustrate the // getName() method on boolean type attribute public class Test {
private boolean empty;
public boolean getName(){
return empty;
}
public boolean isempty(){
return empty;
}
} |
Example of JavaBean Class
Example 1:
Below is the implementation of the JavaBean Class:
// 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 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