FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Mutator_method#Java_example

Mutator method

Contents
    C
    C#
    Delphi
    Java
    ActionScript 3.0
    PHP
    Python
    Ruby
    Rust
    Smalltalk

In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also known collectively as accessors.

The mutator method is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable. Mutator methods can be compared to assignment operator overloading but they typically appear at different levels of the object hierarchy.

Mutator methods may also be used in non-object-oriented environments. In this case, a reference to the variable to be modified is passed to the mutator, along with the new value. In this scenario, the compiler cannot restrict code from bypassing the mutator method and changing the variable directly. The responsibility falls to the developers to ensure the variable is only modified through the mutator method and not modified directly.

In programming languages that support them, properties offer a convenient alternative without giving up the utility of encapsulation.

In the examples below, a fully implemented mutator method can also validate the input data or take further action such as triggering an event.

.code student_get_ageprocobject:DWORD movebx,object moveax,student.age[ebx] ret student_get_ageendp student_set_ageprocobject:DWORD,age:DWORD movebx,object moveax,age movstudent.age[ebx],eax ret student_set_ageendp

C

edit

In file Student.h:

#include<stdlib.h> #include<string.h> #include"Student.h" structStudent{ intage; char*name; }; Student*createStudent(intage,constchar*name){ Student*s=(Student*)malloc(sizeof(Student)); s->name=strdup(name); s->age=age; returns; } voiddestroyStudent(constStudent*s){ free(s->name); free(s); } voidsetStudentAge(Student*s,intage){ s->age=age; } intgetStudentAge(constStudent*s){ returns->age; } char*getStudentName(constStudent*s){ returns->name; }

In file importstd; usingstd::string; classStudent{ private: stringname; public: explicitStudent(conststring&name): name{name}{} [[nodiscard]] conststring&getName()constnoexcept{ returnname; } voidsetName(conststring&name)noexcept{ this->name=name; } };

C#

edit

This example illustrates the C# idea of properties, which are a special type of class member. Unlike Java, no explicit methods are defined; a public 'property' contains the logic to handle the actions. Note use of the built-in (undeclared) variable value.

\n /// Gets or sets student's name\n /// </summary>\n public string Name\n {\n get { return name; }\n set { name = value; }\n }\n}\n"}}'>publicclassStudent { privatestringname; /// <summary> /// Gets or sets student's name /// </summary> publicstringName { get{returnname;} set{name=value;} } }

In later C# versions (.NET Framework 3.5 and above), this example may be abbreviated as follows, without declaring the private variable name.

Students=newStudent; s.name="David";// same effect as student.name("David") stringstudent_name=s.name;// same effect as student.name()

Delphi

edit

This is a simple class in Delphi language which illustrates the concept of public property for accessing a private field.

\n /// Get or set the name of the student.\n /// </summary>\n property Name: string read FName write SetName;\n end;\n\n// ...\n\nimplementation\n\nprocedure TStudent.SetName(const Value: string);\nbegin\n FName := Value;\nend;\n\nend.\n"}}'>interface type TStudent=class strictprivate FName:string; procedureSetName(constValue:string); public /// <summary> /// Get or set the name of the student. /// </summary> propertyName:stringreadFNamewriteSetName; end; // ... implementation procedureTStudent.SetName(constValue:string); begin FName:=Value; end; end.

Java

edit

In this example of a simple class representing a student with only the name stored, one can see the variable name is private, i.e. only visible from the Student class, and the "setter" and "getter" are public, namely the "getName()" and "setName(name)" methods.

functionStudent(name){ var_name=name; this.__defineGetter__('name',function(){ return_name; }); this.__defineSetter__('name',function(value){ _name=value; }); }

Or (using prototypes for inheritance and ES6 accessor syntax):

functionStudent(name){ this._name=name; } Object.defineProperty(Student.prototype,'name',{ get:function(){ returnthis._name; }, set:function(value){ this._name=value; } });

ActionScript 3.0

edit
@interface Student : NSObject @property(nonatomic,retain)NSString*name; @end @implementation Student @synthesizename=_name; @end

And starting with OS X 10.8 and iOS 6, while using Xcode 4.4 and up, syntax can be even simplified:

packageStudent; usebaseqw(Class::Accessor); __PACKAGE__->follow_best_practice; Student->mk_accessors(qw(name)); 1;

Or, using the Moose Object System:

(is => 'rw', isa => 'Str', reader => 'get_name', writer => 'set_name');\n\n1;\n"}}'>packageStudent; useMoose; # Moose uses the attribute name as the setter and getter, the reader and writer properties # allow us to override that and provide our own names, in this case get_name and set_name has'name'=>(is=>'rw',isa=>'Str',reader=>'get_name',writer=>'set_name'); 1;

PHP

edit

PHP defines the "magic methods" __getand__set for properties of objects.

In this example of a simple class representing a student with only the name stored, one can see the variable name is private, i.e. only visible from the Student class, and the "setter" and "getter" is public, namely the getName() and setName('name') methods.

name;\n }\n\n /**\n * @param string $newName The name to set.\n */\n public function setName(string $newName): void\n {\n $this->name = $newName;\n }\n}"}}'>class Student { private string $name; /** * @return string The name. */ public function getName(): string { return $this->name; } /** * @param string $newName The name to set. */ public function setName(string $newName): void { $this->name = $newName; } }

Python

edit

This example uses a Python class with one variable, a getter, and a setter.

None:\n # An instance variable to hold the student's name\n self._name = name\n\n # Getter method-\n @property\n def name(self) -> str:\n return self._name\n\n # Setter method\n @name.setter\n def name(self, new_name: str) -> None:\n self._name = new_name\n"}}'>classStudent: _name: str # Initializer def__init__(self, name: str) -> None: # An instance variable to hold the student's name self._name = name # Getter method- @property defname(self) -> str: return self._name # Setter method @name.setter defname(self, new_name: str) -> None: self._name = new_name
#lang racket (structstudent(name)#:mutable) (defines(student"Alice")) (set-student-name!s"Bob") (student-names); => "Bob"

Ruby

edit

In Ruby, individual accessor and mutator methods may be defined, or the metaprogramming constructs attr_reader or attr_accessor may be used both to declare a private variable in a class and to provide either read-only or read-write public access to it respectively.

Defining individual accessor and mutator methods creates space for pre-processing or validation of the data

classStudent attr_accessor:name end

Rust

edit
&String {\n &self.name\n }\n\n fn name_mut(&mut self) -> &mut String {\n &mut self.name\n }\n}\n\n"}}'>structStudent{ name:String, } implStudent{ fnname(&self)->&String{ &self.name } fnname_mut(&mutself)->&mutString{ &mutself.name } }

Smalltalk

edit
PublicClassStudent Private_nameAsString PublicPropertyName() Get Return_name EndGet Set(ByValvalue) _name=value EndSet EndProperty EndClass

In VB.NET 2010, Auto Implemented properties can be utilized to create a property without having to use the Get and Set syntax. Note that a hidden variable is created by the compiler, called _name, to correspond with the Property name. Using another variable within the class named _name would result in an error. Privileged access to the underlying variable is available from within the class.

Tim Lee (1998-07-13). "Run Time Efficiency of Accessor Functions".
  • ↑ "MOP: Slot Definitions". Retrieved 2011-03-29.
  • ↑ "Object.prototype.__defineGetter__() - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-07-06.
  • ↑

  • View original on Wikipedia | Back | FazBrowse Home