What is a JavaBean exactly?

后端 未结 19 1652
清酒与你
清酒与你 2020-11-22 01:55

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?

<
19条回答
  •  情话喂你
    2020-11-22 02:36

    A Java Bean is any java class that satisfies the following three criteria:

    1. It should implement serializable interface (A Marker interface).
    2. The constructor should be public and have no arguments (What other people call a "no-arg constructor").
    3. It should have getter and setters.

    Good to note the serialVersionUID field is important for maintaining object state. Below code qualifies as a bean:

    public class DataDog implements java.io.Serializable {
    
    private static final long serialVersionUID = -3774654564564563L;
    
    private int id;
    private String nameOfDog;
    
    //The constructor should NOT have arguments
    public DataDog () {}
    
    
    /** 4. getter/setter */
    
    // getter(s)
    public int getId() {
        return id;
    }
    public String getNameOfDog() {
        return nameOfDog;
    }
    // setter(s)
    public void setId(int id) {
        this.id = id;
    }
    public void setNameOfDog(String nameOfDog) {
        this.nameOfDog = nameOfDog;
    }}
    

提交回复
热议问题