Can a JavaBean have methods besides getters and setters?

According to definitions I find in the internet a JavaBean is a Java class that satisfies these conditions:

  • All instance attributes are private
  • All instance attributes have public getters and setters
  • The class has a parameterless constructor
  • The class implements the Serializable interface
  • What I would like to know is that if I add method to a Javabean can we still call it a Javabean?

    For exemple can we say that the following class is a JavaBean?

    public class Person implements Serializable {
        private String name;
        public Person(){}
        public String getName(){...}
        public void setName(String name){...}
        public void sayHello(){}
    }
    

    Yes, Java Beans can definitely have behavior. Java Bean classes without additional methods have very limited applicability, because they encapsulate data devoid of useful behavior.

    Oracle mentions this in one of their tutorials on Java Beans:

    A bean's methods are the things it can do. Any public method that is not part of a property definition is a bean method. When you use a bean in the context of a builder tool like NetBeans, you can use a bean's methods as part of your application. For example, you could wire a button press to call one of your bean's methods.


    Yes, java beans can have additional functionality. The convention was introduced to access properties in a structured way and add functionality like vetoing. It is used for example for GUI components in swing, where the bean mechanism is used to configure the GUI elements. Especially in GUI editors there was the need to dynamically access unknown properties. And of course, these GUI components have lots of functionalities. What you get if you restrict to your set of conditions is a DTO (data transfer object), that only transports data but has no additional functions.

    链接地址: http://www.djcxy.com/p/47656.html

    上一篇: JavaBean和与BeanInfo的关系,它们是相关的吗?

    下一篇: JavaBean除了getter和setter之外还有其他方法吗?