Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JavaBean have methods besides getters and setters?

Tags:

java

javabeans

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(){}
}
like image 205
Chedy2149 Avatar asked Apr 03 '14 15:04

Chedy2149


2 Answers

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.

like image 195
Sergey Kalinichenko Avatar answered Sep 21 '22 02:09

Sergey Kalinichenko


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.

like image 33
Drunix Avatar answered Sep 20 '22 02:09

Drunix