Accessor Methods

Learn what an accessor method is and how to write one in Java.

What is an accessor method?

An accessor method allows other objects to obtain the value of instance variables or static variables. It is a non-void method. A non-void method returns a single value. Its header includes the return type in place of the keyword void. For example:

  • A boolean method should return a variable of the boolean type.
  • An int method should return a variable of the int type.
  • A float method should return a variable of the float type.

In non-void methods, a return expression’s compatibility with the return type is evaluated, and a copy of that value is returned. This is referred to as return by value.

Explanation

Here is an example:

Get hands-on with 1200+ tech skills courses.