JavaBean class in Java

JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions:

  1. Must implement Serializable.
  2. It should have a public no-arg constructor.
  3. All properties in java bean must be private with public getters and setter methods.
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate the
// structure of JavaBean class
public class TestBean {
private String name;
public void setName(String name)
    {
        this.name = name;
    }
public String getName()
    {
        return name;
    }
}

chevron_right


Syntax for setter methods:

  1. It should be public in nature.
  2. The return-type should be void.
  3. The setter method should be prefixed with set.
  4. It should take some argument i.e. it should not be no-arg method.

Syntax for getter methods:

  1. It should be public in nature.
  2. The return-type should not be void i.e. according to our requirement we have to give return-type.
  3. The getter method should be prefixed with get.
  4. It should not take any argument.

For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use “is”.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate the
// getName() method on boolean type attribute
public class Test {
private boolean empty;
public boolean getName()
    {
        return empty;
    }
public boolean isempty()
    {
        return empty;
    }
}

chevron_right


Implementation



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program of JavaBean class
package geeks;
public class Student implements java.io.Serializable
{
private int id;
private String name;
public Student()
    {
    }
public void setId(int id)
    {
        this.id = id;
    }
public int getId()
    {
        return id;
    }
public void setName(String name)
    {
        this.name = name;
    }
public String getName()
    {
        return name;
    }
}

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to access JavaBean class
package geeks;
public class Test {
public static void main(String args[])
    {
        Student s = new Student(); // object is created
        s.setName("GFG"); // setting value to the object
        System.out.println(s.getName());
    }
}

chevron_right


Output:

GFG

This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up