A JavaBeans are the ordinary java classes that should follow the following
conventions:
- The JavaBean class must have a public, no-argument constructor (default constructor).
- The JavaBean class should implement the serializable interface.
- It must have private variables.
- It must have getter and setter methods.
- The JavaBean class attributes must be accessed via accessors (getter method) and mutator (Setter method) methods.
The syntax for setter methods:
public void setName(String name)
- The setter should be public in nature.
- The return type of the setter method should be void.
- It should be prefixed with the set.
- The setter method always takes some argument.
The syntax for getter methods:
public String getName()
- The getter method should be public in nature.
- The return type of getter method should not be void i.e. As per our requirement we have to give return type.
- It should be prefixed with get.
- It doesn't take any argument.
Why we use JavaBeans?
- JavaBeans are reusable software components.
- Using JavaBeans rather than Java Scriptlets in your JSP page allows better separation of the view logic from the business logic.
Example of JavaBean:
class Student{
private int rollno;
private String name;
private int age;
public void setRollno(int rollno){
this.rollno = rollno;
}
public int getRollno(){
return rollno;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
public class JavaBean {
public static void main(String args[]){
Student obj = new Student();
obj.setRollno(111123);
obj.setName("Prashant Srivastava");
obj.setAge(21);
System.out.println("Student rollno is: " +obj.getRollno());
System.out.println("Student name is: " +obj.getName());
System.out.println("Student age is: " +obj.getAge());
}
}
What are JavaBeans?
Reviewed by Prashant Srivastava
on
December 26, 2018
Rating:
No comments: