JavaBean class in Java
Last Updated :
01 Nov, 2023
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
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
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
package geeks;
public class Student implements java.io.Serializable {
private int id;
private String name;
public Student() {}
public void setId( int id) { this .id = id; }
public int getId() { return id; }
public void setName(String name) { this .name = name; }
public String getName() { return name; }
}
|
Example 2:
Below is the implementation of the JavaBean class:
JAVA
package geeks;
public class Test {
public static void main(String args[])
{
Student s = new Student();
s.setName( "GFG" );
System.out.println(s.getName());
}
}
|
Output:
GFG
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...