How to Create a Java Bean

A Java bean is a Java class that has private member variables, public getter and setter methods, and a zero-argument, public constructor (supplied automatically by the compiler). To create a Java bean, follow these seven steps.

Open your text editor and create a new file that will contain the Java bean source. Type in the following Java statements:

The Java bean has two properties, firstName and lastName. A property is a private variable exposed to external programs by means of getter and setter methods.

Save your file as Person.java.

Open your text editor to create the class that will instantiate the Java bean. Type in the following Java statements:

The program will instantiate the Java bean and then call the setter and getter methods of the newly created Java bean.

Save your file as CreateAJavaBean.java.

Open a command prompt and navigate to the directory containing your new Java programs. Then type in the command to compile the Java bean source and hit Enter.

Type in the command to compile the Java application to instantiate the Java bean and hit Enter.

You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. Observe the data from your Java bean.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.