What is a JavaBean exactly?

后端 未结 19 1525
清酒与你
清酒与你 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:43

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题