You’ve heard of JavaBeans. But what are they actually?
Java 1.1. introduced the term JavaBean to describe a self-contained, reusable, high-granularity component. The original idea was to create high-level building blocks for graphical user interfaces (GUI).
Later the term JavaBean was used to describe model objects in a servlet MVC architecture, as well as Enterprise JavaBeans (EJB) business components.
These days, we use the terms JavaBean and POJO (Plain Old Java Object) to mean the same thing.
The benefits of a JavaBean
A JavaBean (or POJO) is a Java class that meets certain coding rules. You will get many benefits from converting your class to a JavaBean:
- You can use a JavaBean inside a servlet or Spring container.
- Your JavaBean can be deserialized correctly.
- You will improve data integrity.
- The JavaBean rules ensure unique names and avoid naming conflicts.
In short, your code becomes more maintainable, and has fewer dependencies on any particular container.
The rules for JavaBeans
The rules to turn a normal Java class into a JavaBean are really easy:
- It must have a default no-argument constructor. This is implicitly called as the first hidden line in a subclass’s constructor. Many programmers assume they can create any object by calling its default constructor, so it’s good practice to provide it. The default no-argument constructor is also used when deserializing objects.
- It must have private instance fields. This is to ensure data hiding.
- It must have public getters and setters that use the standard Java naming conventions.
- It must implement the
Serializable
interface. This is essential if an object needs to be serialized. - It must be placed in a named package. This prevents naming conflicts by ensuring unique class names.
Always?
Should you always turn a Java class into a JavaBean? No, it is not always necessary. But if it’s a model class, there are a lot of practical benefits.
I’m always interested in your opinion, so please leave a comment.