0

"Mandatory" TO-DO's for Java Beans

Posted by Guillermo GarcĂ­a on 7:03 PM in ,
You know what is a Java Bean? You have to, if may say so.

A Java Bean is a Class with a few particular features, but in general, is a data bearer, without any business logic. It may have a little data validation and formating, but that's all. And if you are a good programmer, you will follow the Java Naming Conventions when creating a Java Bean and declaring their getters and setters methods.

So, when you have a data bearer, you want it right. So, you have to overwrite at least, three methods from the Object class.
  1. equals() Because you want to compare two of your brand new objects, and you need to compare it based on their content, and not simply on their references (default behavior of the equals() method)
  2. hashCode() If you change the default behavior of the equals() method, you must change the return value of the hashCode() method, because for example if two objects are considerated equals(), they must return the same hash code (but two different objects can return the same hash code, be aware of this)
  3. toString() If you want your object to be "human readible" you have to define this behavior in the toString() method. This is very important for debugging your code or troubleshooting.

Another point to be stressed is the Serializable interface implementation. If you want your beans to be transported from a media to another (from memory to file system, for example) you must implement the Serializable interface, and you must create an instance variable called "serialVersionUID" which must contain a unique numeric id (This is very important if you want to avoid version issues of your beloved Java Bean)


0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.