Home>Article>Java> How to use Accessor and Mutator in Java?

How to use Accessor and Mutator in Java?

藏色散人
藏色散人 Original
2019-03-22 15:20:37 8228browse

One way to achieve data encapsulation is to use accessors and Mutators. The function of accessors and Mutators is to return and set the value of object state. Let us learn how to write accessors and Mutators in Java. For example, we will use a Person class whose state and constructor are already defined:

How to use Accessor and Mutator in Java?

accessor method

accessors method uses Returns the value of a private field. It follows a naming scheme that puts the "get" prefix at the beginning of method names. For example, let's add Mutator methods for firstname, middleNames, and lastname:

These methods always return the same data type as their corresponding private fields (such as String), and then only return the value of that private field.

We can now access their values through the methods of the Person object:

Mutator method

Use the mutator method to set the value of a private field. It follows a naming scheme that prefixes the word "set" at the beginning of the method name. For example, let's add mutator fields for address and username:

These methods have no return type and accept arguments of the same data type as their corresponding private fields. Then use that parameter to set the value of that private field.

You can now modify the values of the address and username in the Person object:

Why use accessors and Mutator?

We can define the class Change the private field to public and get the same result. It's important to remember that we want to hide the object's data as much as possible. The additional buffers provided by these methods allow us to:

Change how data is processed behind the scenes.

Validate the value that the field is set to.

Suppose we decide to modify the way middle names are stored. We can now use an array of strings instead of a single string:

The implementation inside the object has changed, but the outside world has not been affected. The method is called exactly the same way:

Alternatively, assume that an application using a Person object can only accept usernames of up to 10 characters. We can add validation to the setUsername variable to ensure that the username meets the following requirements:

Now, if the username passed to the setUsername mutator exceeds 10 characters, it will automatically be truncated.

Related recommendations: "Python Tutorial"

The above is the detailed content of How to use Accessor and Mutator in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn