difference between java bean and java class?

Raj picture Raj · Dec 25, 2011 · Viewed 24.4k times · Source

I am new to the JSP and server side programming. Till now I am working with Servlets and java classes. I am segregating my application (as per MVC model) with the help of java classes. I would like to know difference between java beans and java classes. And in which scenario I can use a java bean instead of a java class. Any helpful explanation or helpful links?

Answer

JB Nizet picture JB Nizet · Dec 25, 2011

A Java bean is just a class which conforms to some conventions:

  • properties that can be accessed by getters (and setters if those properties are not read-only)
  • no-arg public constructor
  • serializable

The JSP EL and tags are designed around those conventions. Most of them don't need all these conventions to be respected. properties available by getters is the most important of these conventions. For example, the expression

${foo.bar.name}

displays the name of the bar of the foo bean. foo is a bean that must be in the page, request, session or application context. And this expression will call getBar() on this bean, and then getName() on the object returned by getBar().