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.
// 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;
    }
}

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”.

// 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;
    }
}

Implementation

// 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;
    }
}
// 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());
    }
}

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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.