Method (computer science) 232817 225993302 2008-07-16T10:44:16Z Moondyne 28190 Reverted edits by [[Special:Contributions/121.97.106.111|121.97.106.111]] ([[User talk:121.97.106.111|talk]]) to last version by VolkovBot {{incomplete|date=October 2007}} {{Confusing|date=December 2006}} In [[object-oriented programming]], the term '''method''' refers to a [[subroutine]] that is exclusively associated either with a [[class (computer science)|class]] (called '''class methods''', '''static methods''', or '''factory methods''') or with an [[object (computer science)|object]] (called '''instance methods'''). Like a procedure in [[procedural programming languages]], a method usually consists of a sequence of [[statement (programming)|statements]] to perform an action, a set of input [[parameter (programming)|parameters]] to customize those actions, and possibly an output value (called '''return value''') of some kind. The purpose of methods is to provide a mechanism for accessing (for both reading and writing) the private data stored in an object or a class. ==Java Method modifiers== {| border="2" cellpadding="4" cellspacing="0" style="margin: 1em 1em 1em 0; background: #f9f9f9; border: 1px #aaa solid; border-collapse: collapse; font-size: 95%;" |- bgcolor="#CCCCCC" align="center" ! Access Modifier !! Method Modifier |- | <code>public</code> || <code>abstract</code> |- | <code>private</code> || <code>final</code> |- | <code>protected</code> || <code>native</code> |- | || <code>static</code> |- | || <code>strictfp</code> |- | || <code>synchronized</code> |} It must be noted that improper usage of modifiers of methods may result in unstable software behaviour. ===Kinds of methods=== As stated above, '''instance''' methods are associated with a particular object, while '''class''' or '''static''' methods are instead associated with a class. In all typical implementations, instance methods are passed a hidden [[reference]] (e.g. <code>[[this (computer science)|this]]</code>, <code>[[self (computer science)|self]]</code> or <code>Me</code>) to the object (whether a class or class instance) they belong to, so that they can access the data associated with it. For class/static methods this may or may not happen according to the language; A typical example of a class method would be one that keeps count of the number of created objects within a given class. An '''abstract method''' is a [[dummy code]] method which has no [[implementation]]. It is often used as a placeholder to be [[method overriding (programming)|overridden]] later by a subclass of or an object prototyped from the one that implements the abstract method. In this way, abstract methods help to partially specify a [[framework]]. An '''accessor method''' is a method that is usually small, simple and provides the means for the [[state]] of an object to be accessed from other parts of a program. Although it introduces a new [[dependency (computer science)|dependency]], use of the methods are preferred to directly accessing state data because they provide an [[abstraction layer]]. For example, if a bank-account class provides a <code>getBalance()</code> accessor method to retrieve the current [[balance]] (rather than directly accessing the balance data fields), then later [[revision]]s of the same code can implement a more complex mechanism balance retrieval (say, a [[database]] fetch) without the dependent code needing to be changed. A method that changes the state of an object is no longer called an accessor method, but rather an '''update method''', a '''modifier method''', or a '''[[mutator method]]'''. Objects that provide such methods are considered [[immutable objects|mutable objects]]. Some languages have a special syntax for '''[[Constructor (computer science)|Constructor]]s''', i.e. methods that are called automatically upon the [[object creation|creation]] of an instance of a class. In [[Java (programming language)|Java]], [[C++]], [[C Sharp (programming language)|C#]], [[ActionScript]], and [[PHP]] they are distinguished by having the same name as the class of the object they're associated with (PHP 5 also allows <code>__construct</code> as a constructor); in [[Visual Basic .NET]] the constructor is called <code>New</code>, and in [[Object Pascal]] constructors can have user-defined names (but are mostly called <code>Create</code>). Under [[Objective-C]] the constructor method is split between two methods, <code>alloc</code> and <code>init</code>, with the <code>alloc</code> method setting aside memory for an instance of the class and the <code>init</code> method handling the bulk of initializing the instance; a call to the <code>new</code> method invokes both the <code>alloc</code> and the <code>init</code> method for the class instance. Likewise, some languages have special '''[[Destructor (computer science)|Destructor]]''' methods, i.e. instance methods that are called automatically upon the [[object lifetime|destruction]] of an instance of a class. In C++, they are distinguished by having the same name as the class of the object they're associated with, but with the addition of a [[tilde]] (~) in front (or <code>__destruct</code> in PHP 5). In [[Object Pascal]] destructors can have user-defined names (but are mostly called Destroy). Under [[Objective-C]] the destructor method is named <code>dealloc</code>. ==Isolation levels== Whereas a [[C (programming language)|C]] [[programmer]] might push a value onto a [[Stack (data structure)|stack]] data-structure by calling: :<source lang="c">stackPush(&myStack, value);</source> a [[C++]] programmer would write: :<source lang="cpp">myStack.push(value);</source> The difference is the required level of [[Isolation (computer science)|isolation]]. In C, the <code>stackPush</code> procedure could be in the same source file as the rest of the program and if it was, any other pieces of the program in that source file could see and modify all of the low level details of how the stack was implemented, completely bypassing the intended [[Interface (computer science)|interface]]. In C++, regardless of where the class is placed, only the methods which are part of <code>myStack</code> will be able to get access to those low-level details without going through the formal interface methods. Languages such as C can provide comparable levels of protection by using different [[source file]]s and not providing [[external linkage]] to the private parts of the stack implementation but this is less neat and systematic than the more cohesive and enforced isolation of the C++ approach. == Some recommended usages == A public method should preserve the [[class invariant]]s of the object it is associated with, and should always assume that they are valid when it commences execution (private methods do not necessarily need to follow this recommendation). To this effect, [[precondition]]s are used to constrain the method's parameters, and [[postcondition]]s to constrain method's output, if it has one. If any one of either the preconditions or postconditions is not met, a method may raise an [[exception handling|exception]]. If the object's state does not satisfy its class invariants on entry to or exit from any method, the program is considered to have a [[Software bug|bug]]. The difference between a [[subroutine|procedure]] and a method is that the latter, being associated with a particular object, may access or modify the data private to that object in a way ''consistent with the intended behavior of the object''. Consequently, rather than thinking "a method is just a sequence of commands", a programmer using an object-oriented language will consider a method to be "an object's way of providing a [[Service (systems architecture)|service]]" (its "method of doing the job", hence the name); a method call is thus considered to be a ''request'' to an object to perform some [[task]]. Consequently, method calls are often modeled as a means of [[Message passing|passing a message]] to an object. Rather than directly performing an operation on an object, a message (most of the time accompanied by parameters) is sent to the object telling it what it should do. The object either complies or raises an exception describing why it cannot do so. Applied to our stack example, rather than pushing a value onto the stack, a value is sent to the stack, along with the message ''"push"''. ==Static methods== As mentioned above, a method may be declared as static (or <code>Shared</code> in [[Visual Basic .NET]]), meaning that it acts at the class level rather than at the instance level. Therefore, a static method cannot refer to a specific instance of the class (i.e. it cannot refer to <code>this</code>, <code>self</code>, <code>Me</code>, etc.) An example of a static member and its consumption in [[C Sharp (programming language)|C#]] code: <source lang="java"> public class ExampleClass { public static void StaticExample() { // static method code } public void InstanceExample() { // instance method code here // can use THIS } } /// Consumer of the above class: // Static method is called -- no instance is involved ExampleClass.StaticExample(); // Instance method is called ExampleClass objMyExample = new ExampleClass(); objMyExample.InstanceExample(); </source> Confusingly, methods marked as <code>class</code> in Object Pascal also cannot refer to a class object, as can class methods in [[Python (programming language)|Python]] or [[Smalltalk (programming language)|Smalltalk]]. For example, this Python method can create an instance of <code>Dict</code> or of any subclass of it, because it receives a reference to a ''class object'' as <code>cls</code>: <source lang="python"> class Dict: @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d </source> == See also == *[[Implementation inheritance]] *[[Inheritance semantics]] *[[Subroutine]] *[[Virtual inheritance]] *[[Method name]] *[[Idempotence]] [[Category:Method (computer science)|*]] [[be-x-old:Мэтад (праграмаваньне)]] [[bs:Računarska metoda]] [[de:Objektorientierte Programmierung#Methoden]] [[et:Meetod (programmeerimine)]] [[es:Método (programación orientada a objetos)]] [[fr:Méthode (informatique)]] [[it:Metodo (programmazione)]] [[lt:Metodas (programavimas)]] [[nl:Methode (objectoriëntatie)]] [[ja:メソッド (計算機科学)]] [[pl:Metoda (programowanie obiektowe)]] [[ru:Метод (языки программирования)]] [[sv:Metod (programmering)]] [[ta:செயலி (கணினியியல்)]] [[uk:Метод (програмування)]] [[zh:方法 (電腦科學)]]