Bean in Java

For understanding the bean concept in Java, suppose we don’t want our declared variables to be shared so we simply make them private. But what if we want to access them or change their data without directly accessing that variable. In that case, we need to use some type of method which not only changes the variable’s data but also accesses them from the outside world.

Here we go with the concept of Java Bean. Java Bean is a class that should follow some rules of writing like given below:

  • No constructor in the class.
  • The class should have set data and get data methods declared in it.
  • The class should be Serializable.

Let’s take an example: In a class, we will declare some variables and will make them private so that the outside world cannot access them. In the same class with no constructor, we will define setters and getters methods to set and get/fetch the data. In Java, these methods should have ‘set’ and ‘get’ as prefixes in the method name so that Java will automatically detect set and get methods.

Example:

public class Student implements java.io.Serializable{
    private int roll_no;
    private String name;
    public void setRollno(int n){
        roll_no=n;
    }
    public void getRollno(){
        return roll_no;
    }
    public void setname(String name){
        this.name=name;
    }
    public void getname(){
        return name;
    }
}

Now here we have defined a class Student and as the third rule says class should be serializable so we have implemented a serializable class. In the Student class, we have declared two variables as private and we can access them by getter method and changing their data by setter method.

Now in another class let’s say College class, we will create an object of student class and try to fetch and change the data.

public class College{  
    public static void main(String args[]){  
        Student e=new Student();//object is created  
        e.setname("Priya");//setting value to the object  
        e.setRollno(44); 
        System.out.println(e.getname());  // getting data and printing them
        System.out.println(e.getRollno());  
    }
}

See, how convenient the Java Bean is. We haven’t used direct assignment and direct access of variables so it also follows encapsulation.

That’s all for this tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *