What are JavaBeans?

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).
  • 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)
  1. The setter should be public in nature.
  2. The return type of the setter method should be void.
  3. It should be prefixed with the set.
  4. The setter method always takes some argument.


The syntax for getter methods:

                   public String getName()
  1. The getter method should be public in nature.
  2. The return type of getter method should not be void i.e. As per our requirement we have to give return type.
  3. It should be prefixed with get.
  4. 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());
 }
}

Output:
JavaBeans

What are JavaBeans? What are JavaBeans? Reviewed by Prashant Srivastava on December 26, 2018 Rating: 5

No comments:

Powered by Blogger.