JavaBeans Naming Standards

Author: Tatyana Milkina

Identifiers and JavaBeans: Understanding Naming Conventions photo

The JavaBeans are Java classes that contain properties. We can think of properties as private instance variables. Because they're private, they can be accessed from outside their class only by the class methods. The methods that receive a property's value are called getter methods, and the methods that change a property's value are called setter methods. The JavaBeans naming rules:

  • If the property is not a boolean, the getter method's prefix should be getting. For example, getName() is a valid JavaBeans getter name for a property named "name." It isn't required to have a variable named "name". The name of the property is inferred from the getters and setters, not through any variables in the class.
  • If the property is a boolean, the getter method's prefix is either get or is. For example, getPrinted() or isPrinted() are both valid JavaBeans names for a boolean property.
  • The setter method's prefix should be set. For example, setName() is the valid JavaBean name for a property named "name".
  • To create the name of a getter or setter method, the first letter of the property name should be changed to uppercase and appended to the appropriate prefix (set, get, or is).
  • Setter method signatures should be public, have a void return type, and an argument that represents the property type.
  • Getter method signatures should be public, take no arguments, and have a return type that matches the argument type of the setter method for that property.

The JavaBean specification supports events, which gives the possibility to notify components when some event occurs. The objects that retrieve the info that an event happened are called listeners. The methods which are used to add or remove listeners from an event should also follow JavaBean naming standards:

  • Listener method names that "register" a listener with an event source should use the prefix add, followed by the listener type: addActionListener().
  • Listener method names that remove a listener should use the prefix remove, followed by the listener type.
  • The type of listener to be added or removed should be passed as the argument to the method.
  • Listener method names should end with the word "Listener".
Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Комментарии