A Simple JavaBeans Tutorial

A JavaBean is a specialized Java class. In this short JavaBeans tutorial, I’ll show you the rules with which a JavaBean must comply and then I’ll give you examples of creating a JavaBean, first in straight Java and then in JSP.

JavaBean Rules

  • A JavaBean must have a public, no-argument constructor (a default constructor). This is required so that Java frameworks can facilitate automated instantiation.
  • The JavaBean class attributes must be accessed via accessor and mutator methods that follow a standard naming convention (getXxxx and setXxxx, isXxxx for boolean attributes). It’s important to note that an “attribute” is a named memory location that contains a value, while a “property” refers to this set of methods used to access an attribute. This allows frameworks to automate operations on attribute values.
  • The JavaBean class should be serializable. This allows Java applications and frameworks to save, store, and restore the JavaBean’s state.

JavaBean Example

Here is a simple JavaBean example:

// The class is serialized for IO operations
public class Person implements java.io.Serializable {
	// attributes declared as private
	private String name;
	private boolean deceased;
 

	// Default Constructor
	public Person() { }

	// getXxxx to access the name attribute
	public String getName() {
		return this.name;
	}

	// setXxxx to mutate the name attribute
	public void setName(String name) {
		this.name = name;
	}

	// isXxxx to access boolean attribute
	public boolean isDeceased() {
		return this.deceased;
	}

	// setXxxx to mutate boolean attribute
	public void setDeceased(boolean deceased) {
		this.deceased = deceased;
	}
}

JavaBean Example with JSP

This JavaBean can be implemented by a JavaServer Page (JSP) without all the code used to instantiate it and initialize its attributes:




In my next article, I’ll delve into this JSP/JavaBean relationship a bit more.

JavaBeans are covered in different forms through Webucator’s Java classes.

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.