Method (computer programming): Difference between revisions

Content deleted Content added
No edit summary
No edit summary
Line 12:
The difference between a function and a method is that a method, being associated with a particular object, will access or modify some [[aspect]] of that object. Consequently, rather than thinking "a function is a grouped set of commands", an OO programmer will consider a method to be "this object's way of providing a [[service]]" (its "method of doing the [[job]]", hence the name); a method call should be considered to be a request to the object to perform a [[task]]. Method calls are often modelled as a means of passing a [[message]] to an object. Rather than pushing a value onto the stack, we send a value to stack, along with the message "push!", and the stack complies or raises an [[exception (computer science)|exception]] to explain why it cannot.
 
An '''instance method''' is a method invoked with respect to an [[instance]] of a [[class (computer science)|class]]. Instance methods are often used to examine or modify the [[state (computer science)|state]] of a particular [[object (computer science)|object]]. In [[Java programming language|Java]] and [[C Plus Plus|C++]], '''constructors[[constructor]]s''' are special instance methods that are called automatically upon the [[object creation|creation]] of an instance of a class; they are distinguished by having the same name as their class. In typical implementations, instance methods are passed a hidden [[reference]] (e.g. "[[this]]" or "[[self]]") to the object they belong to, so that they can access the data associated with the instance that they are called upon.
 
In contrast to instance methods, a '''class method''' ('''shared method''') can be invoked without reference to a particular [[object (computer science)|object]]. These affect an entire [[Class (computer science)|class]], not merely a particular instance of the class. A typical example of a class method would be one that keeps count of the number of created objects within a given class. Some programming languages such as C++ and Java call them '''static method''' since methods are modified with <code>static</code>.