Java Seminar
JAVA BEANS :
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 :
1.getPropertyName() :
■For example, if property name is firstName, your method name would be getFirstName() to read that property.
■This method is called accessor.
Properties of getter methods are as follows:
■ Must be public in nature
■Return-type should not be void
■The getter method should be prefixed with the word get
■It should not take any argument.
2.setPropertyName() :
■ For example, if property name is firstName, your method name would be setFirstName() to write that property.
■ This method is called mutator.
Properties of setter methods:
■Must be public in nature
■Return-type should be void
■The setter method has to be prefixed with the word set
■It should take some argument
■ A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.
Example :
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("Srinivasan");
System.out.println(bean.getFirstName());
}
}
Output :
Srinivasan
Comments
Post a Comment