Which of the following is a benefit of using a mutator method?

mutator and accessor term is unknown for me please explain any one

  • 39442 Views
  • 11 Answers

11 Answers

    • 12 May
    • 0 Comments

    • 10 Feb
    • 0 Comments

    • 07 Feb
    • 0 Comments

    • 20 Jan
    • 0 Comments

    • 20 Jan
    • 0 Comments

    • 19 Jan
    • 0 Comments

    • 19 Jan
    • 0 Comments

    • 19 Jan
    • 0 Comments

    • 18 Jan
    • 0 Comments

    • 18 Jan
    • 0 Comments

Dicussion/Forum

Core Java

In Python, class is a prototype for objects which is a user-defined type. It specifies and defines objects of the same type, a class includes a cluster of data and method definitions. Moreover, an object is a single instance of a class but you can create many objects from a single class.
Note: For more information, refer to Python Classes and Objects
 

Accessor and Mutator methods

So, you all must be acquainted with the fact that the internal data of an object must be kept private. But there should be some methods in the class interface that can permit the user of an object to access and alter the data (that is stored internally) in a calm manner. Therefore, for that case we have two methods namely Accessors and Mutators that are helpful in accessing and altering respectively, internally stored data. 
 

  • Accessor Method: This method is used to access the state of the object i.e, the data hidden in the object can be accessed from this method. However, this method cannot change the state of the object, it can only access the data hidden. We can name these methods with the word get. 
     
  • Mutator Method: This method is used to mutate/modify the state of an object i.e, it alters the hidden value of the data variable. It can set the value of a variable instantly to a new value. This method is also called as update method. Moreover, we can name these methods with the word set. 
     

Below examples illustrate the use of Accessor and Mutator methods in Python: 
Example 1: 
 

arr = array.array('i', [5, 1, 3, 4, 2, 2, 7])

Output:  4 2 array('i', [5, 1, 3, 4, 2, 2, 7, 19])

So, here the index() and count() method only accesses the data so they are accessor methods but the append() method here modifies the array so its a mutator method. 
Example 2: 
 

    def __init__(self, carname):

    def set_make(self, carname):

So, here the name of the car was accessed using Accessor method i.e, get_make and then it was modified using Mutator method i.e, set_make.
 


Article Tags :

In Java, the keywords public and private define the access of classes, instance variables, constructors, and methods.

private restricts access to only the class that declared the structure, while public allows for access from any class.

Posted by Marta on December 4, 2021 Viewed 16342 times

Which of the following is a benefit of using a mutator method?

In this article, you will learn what a mutator method in java and accessor method. Additionally, you will understand the benefits of using mutator and accessor methods and see some java examples.

The mutator and accessor method concepts are closely related to object-oriented programming and encapsulation. In case you are not familiar with object-oriented programming. I have included a brief introduction below; however, if you would like further details, check out the documentation.

Watch this tutorial on Youtube

Object-Oriented Programming Recap

Object Oriented Programming means that you solve problems representing the entities of the problem as classes. A class has a state and methods where the state is a set of variables containing the relevant data in our representation. And the methods determine the operations our class can perform.

For example, we can define the class Circle:

public class Circle { private float radius; public Circle(float newRadius) { this.radius = newRadius; } public double area(){ return Math.PI * Math.pow(radius, 2); } }

This class is representing the circle concept. The circle class state has the radius and a method named area(), which returns the circle area.

You can add the following code to the Circle class to test it out:

public static void main(String[] args){ Circle circle1 = new Circle(3); System.out.println(circle1.area()); }

Output:

Encapsulation Recap

We have defined a class using object-oriented programming and created the object circle1 of the class Circle. What if I wanted to modify the radius of the object circle1. As the code stands, I can’t change it since there no method to access the radius variable. All I can do is creating a new Circle object with a different radius. What can I do to correct this?

You can do two things; one will lead to a well-designed class, and the other to a poor, challenging to maintain design. One option is declaring the radius field as a public field, so it is accessible outside the class. See the changes below:

public class Circle { public float radius; public Circle(float newRadius) { this.radius = newRadius; } public double area(){ return Math.PI * Math.pow(radius, 2); } public static void main(String[] args){ Circle circle1 = new Circle(3); System.out.println(circle1.radius); circle1.radius = 5; System.out.println(circle1.radius); } }

Output:

The other option is creating methods to access and modify the radius field, which allows you to hide the implementation details. This mechanism is also known as encapsulation.

Mutator Method Definition in Java

The mutator method in java, and any object-oriented programming language, is a method that enables you to change the variables inside the class. Private is the access-level for the variables, meaning the only way to change the variables is by using the mutator methods. This way, the mutator methods can control the validity and quality of the data saved in the class. 

For example, in the previous code snippet, the setRadius() method is a mutator method. You could modify this method to add some data validation. For instance, an example of data validation could be checking if the new radius is a negative number.

Accessor Method Definition in Java

Accessor methods are methods that allow reading the class fields to other methods or classes outside the class. This way enables you to control how the client code can access the class fields.

Mutators and Accessors Examples

Let’s see some examples to illustrate the mutator and accessor methods. Setters and getters is another way of referring to accessor and mutator methods.

Below there is an example of how to add getters to a class. The class is called Product, and it has two getters: getPrice() and getName(). These methods allow any client code to access the class variable, which is price and name.

import java.math.BigDecimal; public class Product { private BigDecimal price; private String name; // getter or accessor methods public BigDecimal getPrice() { return price; } public String getName() { return name; } }

And now, I will add the mutators, so I can access and modify the class variable.

import java.math.BigDecimal; public class Product { private BigDecimal price; private String name; public BigDecimal getPrice() { return price; } public String getName() { return name; } // mutator or setter methods public void setPrice(BigDecimal price) { if(price.compareTo(BigDecimal.ZERO)<0 )throw new IllegalArgumentException("Empty product name"); this.price = price; } public void setName(String name) { if(name.isEmpty()) throw new IllegalArgumentException("Empty product name"); this.name = name; } }

As you can see above, the setter methods setPrice() and setName() also include validation, making sure the data passed meet some criteria. For example, one of the requirements is that a price should always be above zero. In case the parameter is not valid, the code will throw an exception. Otherwise, it will assign the new value.

Naming Conventions for Mutators

In java, the names of these methods, accessors, and mutators should follow specific naming conventions. These rules are entirely stabilized, which makes them essential to follow. Not following these conventions can create frustration and confusion when other people are reading your code.

Let’s start with the naming conventions for mutators. The method should be declared as public and return void. Moreover, the method name should begin with the word set in lowercase. Followed by the class variable name with an initial capital letter. For instance, if our class has a variable called age, then the mutator method should look as follows:

public void setAge(int age){...}

Naming Conventions for Accessors

Along with mutators, we have seen the accessors, which also follow a similar naming convention. The rules are that the method should be declared as public. Additionally, the method name should start by get, followed by the class variable name with an initial capital letter. The method has no parameters and returns the instance variable type. Following the previous example, let’s create an accessor method for the age variable:

Benefits of Mutators and Accessors

So far, we have seen the accessor and mutator methods in java with some examples. And familiarize ourselves with the naming conventions that you should follow when declaring these methods. However, how are these methods useful? The main benefit is encapsulation. This basically means that by creating these methods, you are hiding the internal details of your class from other components. Other components can only communicate via the API.

Consequently, classes are decoupled; they don’t depend on each, allowing you to develop in isolation, which leads to faster developments since team members can create different classes and components in parallel. Besides easing maintenance, since components can be modified, with a small impact on other dependant components.

Conclusion

To summarise, in this article, we have seen that mutator methods and accessors methods in java are methods that enable us to read and write class variables. Their primary purpose is helping us to design classes that are well encapsulated and decoupled from each other.

I hope you find the article useful, and thank you so much for reading and supporting this blog! Happy coding!

How to Write a Tic Tac Toe Game in Java using classes

Matplotlib guide : Custom a graph – Imshow, Colorbar, etc

Django: order by and filter with examples

Python Errors: Nameerror name is not defined and more

What is the use of return in python programming?