What is a JavaBean exactly?

695,935

Solution 1

A JavaBean is just a standard

  1. All properties are private (use getters/setters)
  2. A public no-argument constructor
  3. Implements Serializable.

That's it. It's just a convention. Lots of libraries depend on it though.

With respect to Serializable, from the API documentation:

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

In other words, serializable objects can be written to streams, and hence files, object databases, anything really.

Also, there is no syntactic difference between a JavaBean and another class -- a class is a JavaBean if it follows the standards.

There is a term for it, because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).

Solution 2

There's a term for it to make it sound special. The reality is nowhere near so mysterious.

Basically, a "Bean":

  • is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
  • has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
  • has a public zero-argument constructor (so it can be created at will and configured by setting its properties).

As for Serializable: That is nothing but a "marker interface" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) "serialization" -- a process that converts an instance into a stream of bytes. Those bytes can be stored in files, sent over a network connection, etc., and have enough information to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!

Of course, in order to do that, the class has to abide by certain limitations. Chief among them is that all instance fields must be either primitive types (int, bool, etc.), instances of some class that is also serializable, or marked as transient so that Java won't try to include them. (This of course means that transient fields will not survive the trip over a stream. A class that has transient fields should be prepared to reinitialize them if necessary.)

A class that can not abide by those limitations should not implement Serializable (and, IIRC, the Java compiler won't even let it do so.)

Solution 3

JavaBeans are Java classes which adhere to an extremely simple coding convention. All you have to do is to

  1. implement the java.io.Serializable interface - to save the state of an object
  2. use a public empty argument constructor - to instantiate the object
  3. provide public getter/setter methods - to get and set the values of private variables (properties).

Solution 4

Properties of JavaBeans

A JavaBean is a Java object that satisfies certain programming conventions:

  1. The JavaBean class must implement either Serializable or Externalizable

  2. The JavaBean class must have a no-arg constructor

  3. All JavaBean properties must have public setter and getter methods

  4. All JavaBean instance variables should be private

Example of JavaBeans

@Entity
public class Employee implements Serializable{

   @Id
   private int id;
   private String name;   
   private int salary;  

   public Employee() {}

   public Employee(String name, int salary) {
      this.name = name;
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName( String name ) {
      this.name = name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

Solution 5

Explanation with an example.

1. import java.io.Serializable

As for the Serialization, see the documentation.

2. private fields

Fields should be private for prevent outer classes to easily modify those fields. Instead of directly accesing to those fields, usuagly getter/setter methods are used.

3. Constructor

A public constructor without any argument.

4. getter/setter

Getter and setter methods for accessing and modifying private fields.

/** 1. import java.io.Serializable */
public class User implements java.io.Serializable {
    /** 2. private fields */
    private int id;
    private String name;

    /** 3. Constructor */
    public User() {
    }
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    /** 4. getter/setter */
    // getter
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    // setter
    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
}
Share:
695,935
Amir Rachum
Author by

Amir Rachum

Programmer, Board Gamer, Geek. Blog, Resume and Projects: http://amir.rachum.com/blog Twitter: @AmirRachum

Updated on July 08, 2022

Comments

  • Amir Rachum
    Amir Rachum almost 2 years

    I understood, I think, that a "Bean" is a Java-class with properties and getters/setters.
    As much as I understand, it is the equivalent of a C struct. Is that true?

    Also, is there a real syntactic difference between a JavaBean and a regular class?
    Is there any special definition or an Interface?

    Basically, why is there a term for this?

    Also what does the Serializable interface mean?

    • Matthew Flaschen
      Matthew Flaschen almost 14 years
      See places where Java Beans used?. It's a class following certain conventions.
    • informatik01
      informatik01 over 10 years
      For the sake of completeness, here is a link to the JavaBeans Specification.
    • Bill K
      Bill K about 5 years
      Just a note. If you ever hear people throw around the term POJO, they often actually mean Bean. When you see POJOs they nearly always have setters & getters, are serializable, … In actuality a POJO does not require setters and getters, a serializable interface or anything else--it is simply a Plain Old Java Object with no specific requirements.
    • Don Rolling
      Don Rolling about 3 years
      Definitely not a struct, but I'm glad you asked the question.
  • AndaP
    AndaP over 11 years
    Right on, in my opinion almost all documentation revolving around beans can't describe the term as concisely as you have. +1
  • worldsayshi
    worldsayshi about 11 years
    Is it required for the members of a bean to also be beans? Seems like a reasonable requirement..
  • Viliam Búr
    Viliam Búr almost 11 years
    @worldsayshi - No, it's not required. For example a bean can contain a String; and String is not a bean. (String is immutable, so you cannot create it by calling an empty constructor and a setter.) It seems reasonable that a Serializable object should have Serializable members, unless it somehow serializes them from outside. So no, Java bean members do not need to have any aspect of Java beans. Although it is more simple if they are beans, too.
  • Hanfeng
    Hanfeng over 10 years
    Could you please provide more information about deploying project across multiple servers? thank you
  • Truong Ha
    Truong Ha over 10 years
    say a cluster with a couple of servers, for Websphere this link stackoverflow.com/questions/3193345/… might help.
  • giannis christofakis
    giannis christofakis over 8 years
    Are the annotations necessary or part of a Java Bean?
  • Tianxiang Xiong
    Tianxiang Xiong over 8 years
    @giannischristofakis No, the annotations are not necessary. The annotations are used part of the Spring Framework, which uses Java Beans extensively.
  • Puce
    Puce over 8 years
    "All properties private" is not correct. Properties are inferred from the getters and setters (if there is a method X getFoo() -> the bean has a readable property called "foo"; if there is a method setFoo(X foo) -> the bean has a writeable property called "foo"). Properties can be backed by member fields (but don't have to be) which are usually private.
  • Renato
    Renato over 8 years
    Why does it need to have a no-arg constructor?
  • Alex75
    Alex75 about 8 years
    @Renato this is very simple. think about spring that must instantiate automatically your bean with arg-constructor ... what will it pass as arguments? ;)
  • Satyabrata sahoo
    Satyabrata sahoo almost 8 years
    I hope for being a Java bean "a class must be Public". And is it really need that it should implement Serializable Interface??
  • ncmathsadist
    ncmathsadist almost 8 years
    It sounds as if you should not declare state variables final, because you have a no-args constructor. Is this right?
  • mike rodent
    mike rodent over 7 years
    Useful post and link. When I think of beans I do indeed think thing of "Visual Builder" type stuff, as illustrated in the Oracle article. I wonder whether there are many other frameworks which use them in a big way...
  • kingfrito_5005
    kingfrito_5005 over 7 years
    This is probably a stupid question but, what could an instance field be besides a primitive type or an instance of a class?
  • cHao
    cHao over 7 years
    @kingfrito_5005: It's going to be one or the other. But if it's an instance of a class, it matters whether that class is serializable or not. In order for a class to be serializable, its non-transient parts have to be of some serializable type.
  • Rodney P. Barbati
    Rodney P. Barbati over 7 years
    I like the phrase "reusable software component" when talking about java beans - because java beans in general do absolutely nothing.
  • Paul Wintz
    Paul Wintz almost 7 years
    @ncmathsadist, yes, that must be the case.
  • Amos Kosgei
    Amos Kosgei over 5 years
    probably forgot to mention that the constructor should have no arguments . has a public default constructor (so it can be created at will and configured by setting its properties).
  • cHao
    cHao over 5 years
    @AmosKosgei: Didn't forget; it'd just be redundant. A default constructor by definition can be called with no arguments.
  • cHao
    cHao over 5 years
    @Amos: As i look into it, though, it seems "default constructor" means something slightly different in Java from in C++. :P Replaced "default" with "0-arg".
  • mavili
    mavili over 5 years
    Thanks a lot! Why did I have to search everywhere to get to this? Why cannot people be as to the point as you have been with your answer?!! Such a hugely un-intuitive term for such a simple standard.
  • steven7mwesigwa
    steven7mwesigwa over 5 years
    i guess for setId(int id) body you meant to say this.id = id; instead of this.id = is;
  • OzzyTheGiant
    OzzyTheGiant about 5 years
    @Puce I think that misnomer is due to the fact that in other OOP languages, member fields are called properties (JavaScript, PHP) or instance variables (Python). People seem to use these terms interchangeably.
  • ARK
    ARK about 5 years
    Right on - violates "don't ask an object for it's values, ask an object to do something for you")
  • Giorgi Tsiklauri
    Giorgi Tsiklauri over 4 years
    That's all very concise, clear and nice; however, nowadays, a lot of people (in courses, tutorials, or even talks) refer the the @Entity (javax.persistence.entity) as to the Javabean class annotated with @Entity (for ORM mapping).. and.. @Entity classes do not implement java.io.Serializable.. that's what usually confuses me a bit, as I'm a very picky and perfectionist type of person. Is @Entity a Javabean or something close to Javabean?
  • NateW
    NateW almost 4 years
    Probably also worth mentioning that the getters and setters have to follow a certain naming convention. So if your getter for "foo" is called "getFoo()", you're good. But if you called it something dumb like "acquireTheValueOfTheFooVariable()" (just as a silly example) then it wouldn't be a bean. I'm not sure if Boolean getters are allowed to start with "is" instead of "get"
  • Peter Mortensen
    Peter Mortensen over 3 years
    Wasn't this already covered by previous answers?
  • Peter Mortensen
    Peter Mortensen over 3 years
    @Rodney P. Barbati: Yes, but it looks plagiarised to me (though a search was unsuccessful). In at least 2016, 2017, and 2018, the OP left out most articles (see other posts, e.g. this example from 2018), but in this post, most articles are included. Or in other words, the writing style in this post does not fit the writing style of the OP's other posts ca. 2016.
  • Peter Mortensen
    Peter Mortensen over 3 years
    Walls of text. Can you break them down? Perhaps also add subsection titles.
  • Farid
    Farid about 3 years
    Instead of word junk like to facilitate code reuse and component-based software engineering, i.e. enable developers to build applications by assembling existing components (classes) and without having to write any code (or only have to write a little glue code). you could have given an example as what you mean by "acilitate code reuse"
  • Farid
    Farid about 3 years
    I'm quite sure OP (and most of us) are here for an explanation rather than copy-paste text
  • Farid
    Farid about 3 years
    What is this even intended to be?
  • rps
    rps about 3 years
    Hi @Farid Lack of sub-sectioning, as pointed out by Peter Mortensen here in comment, might have inhibited some readability/comprehensibility. Otherwise, I had read most answers here before posting my answer and tried to write a better one. You may read it now and would be glad to hear your specific comments.
  • wlnirvana
    wlnirvana about 3 years
    This answer deserves more upvotes. Not only does it clarify some misunderstanding on JavaBeans (e.g. public zero-args constructor is just convention rather than the only option allowed by the spec), but it compares JavaBeans with many other commonly seen beans to provide a wider context. Well summarized.
  • TheRealChx101
    TheRealChx101 almost 3 years
    What are you crying about? What difference would class and struct make/be? Wouldn't the JVM implementation be the same?, something like a v-table?
  • Adam Gent
    Adam Gent over 2 years
    Yes all the comments are horrifically wrong. Java Beans can even be immutable through @java.beans.ConstructorProperties. The original spec is so outdated it doesn't even make since. The only real "standard" is what is defined in java.beans.Introspector. The only logic that class really does is check if there are methods that have is/get/set.
  • Mixed_Signals
    Mixed_Signals over 2 years
    After diving deep down the rabbit hole that is JavaBeans myself, I absolutely agree with this answer. JavaBeans are deeply misunderstood concept in the Java community. The original JavaBeans spec makes no mention of a nullary constructor. Only that fields can be accessed through appropriately named getters/setters. This misinterpretation seems to extend into most frameworks as well. Most frameworks specify that they only work with JavaBean objects, when in reality they mean that the objects they work with must adhere to the getter/setting naming conventions set forth by the JavaBeans spec.
  • Nathan
    Nathan almost 2 years
    This explanation is beautiful. I checked like 5 websites for what 'transient' means and this is the one that made it clear to me.