Accessor Methods
Explore accessor methods in Java, which allow controlled access to private instance variables. Understand how non-void methods return values, differences between primitive and object return types, and the role of the toString method for object description. This lesson helps you grasp key concepts for managing class data securely and effectively.
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
booleanmethod should return a variable of thebooleantype. - An
intmethod should return a variable of theinttype. - A
floatmethod should return a variable of thefloattype.
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 ...