JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions:
- Must implement Serializable.
- It should have a public no-arg constructor.
- All properties in java bean must be private with public getters and setter methods.
| // Java program to illustrate the// structure of JavaBean classpublicclassTestBean {privateString name;publicvoidsetName(String name)    {        this.name = name;    }publicString getName()    {        returnname;    }} | 
Syntax for setter methods:
- It should be public in nature.
- The return-type should be void.
- The setter method should be prefixed with set.
- It should take some argument i.e. it should not be no-arg method.
Syntax for getter methods:
- It should be public in nature.
- The return-type should not be void i.e. according to our requirement we have to give return-type.
- The getter method should be prefixed with get.
- 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 attributepublicclassTest {privatebooleanempty;publicbooleangetName()    {        returnempty;    }publicbooleanisempty()    {        returnempty;    }} | 
Implementation
| // Java Program of JavaBean classpackagegeeks;publicclassStudent implementsjava.io.Serializable{privateintid;privateString name;publicStudent()    {    }publicvoidsetId(intid)    {        this.id = id;    }publicintgetId()    {        returnid;    }publicvoidsetName(String name)    {        this.name = name;    }publicString getName()    {        returnname;    }} | 
| // Java program to access JavaBean classpackagegeeks;publicclassTest {publicstaticvoidmain(String args[])    {        Student s = newStudent(); // 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 Lazyroar 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 Lazyroar 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.


 
                                    







