What are JavaBeans? - Javastudypoint

Wednesday, December 26, 2018

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.
Java Beans
Java Beans


 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:

// Java Program of JavaBean class.
package com.javastudypoint;

public class Student implements java.io.Serializable {
    private int rollno;
    private String name;

    public void setRollno(int rollno)      // setter method
    {
        this.rollno = rollno;
    }
    public int getRollno()                   // getter method
    {
        return rollno;
    }

     public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return name;
    }
}

// Java Program to access the JavaBean class.
package com.javastudypoint;

public class JavaBeans
{
    public static void main(String arg[])
    {
        Student st = new Student();   // Student class object is created
        st.setName("Prashant Srivastava");  // setting the value to object.
        System.out.println( st.getName());
    }
}


Output:




No comments:

Post a Comment