JavaBean class in Java

Java 8Object Oriented ProgrammingProgramming

A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

  • It provides a default, no-argument constructor.

  • It should be serializable and that which can implement the Serializable interface.

  • It may have a number of properties which can be read or written.

  • It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including the classes that you define.

A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean's implementation class −

Sr.No.Method & Description
1getPropertyName()
For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.
2setPropertyName()
For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.

Example

 Live Demo

class StudentsBean implements java.io.Serializable {
   private String firstName = null;
   private String lastName = null;
   private int age = 0;
   public StudentsBean() {
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public void setAge(Integer age) {
      this.age = age;
   }
}
public class Tester {
   public static void main(String[] args) {
      StudentsBean bean = new StudentsBean();
      bean.setFirstName("Mahesh");
      System.out.println(bean.getFirstName());
   }
}

Output

Mahesh
raja
Published on 01-Nov-2018 09:35:20
Advertisements