Method (computer programming): Difference between revisions

Content deleted Content added
Link suggestions feature: 2 links added.
 
(651 intermediate revisions by more than 100 users not shown)
Line 1:
{{short description|Function that is tied to a particular instance or class}}
In [[computer science]], a '''method''' is a [[function]] or [[subroutine]] that is associated with a [[class (computer science)|class]] in [[object-oriented programming]]. Like a function in procedural languages, it may contain a set of program statements that perform an action, and (in most [[computer language]]s) can take a set of input arguments and can return some kind of result.
 
A '''method''' in [[object-oriented programming]] (OOP) is a [[Procedure (computer science)|procedure]] associated with an [[Object (computer science)|object]], and generally also a [[Message passing|message]]. An object consists of ''state data'' and ''behavior''; these compose an [[Interface (object-oriented programming)|''interface'']], which specifies how the object may be used. A method is a behavior of an object parametrized by a user.
Whereas a [[C]] [[programmer]] might push a value onto a [[stack_(software)|Stack]] data-structure by calling:
stackPush(&myStack, value);
a [[C Plus Plus|C++]] programmer would write:
myStack.push(value);
 
Data is represented as [[Property (programming)|properties]] of the object, and behaviors are represented as methods. For example, a <code>Window</code> object could have methods such as <code>open</code> and <code>close</code>, while its state (whether it is open or closed at any given point in time) would be a property.
the difference being that in C, the function is just a set of instructions; in C++, the push method is intimately associated with the Stack class; its implementation will typically be granted access to the Stack's state which other parts of the program cannot reference.
 
In [[class-based programming]], methods are defined within a [[class (computer science)|class]], and objects are [[Instance (computer science)|instances]] of a given class. One of the most important capabilities that a method provides is ''[[method overriding]]'' - the same name (e.g., <code>area</code>) can be used for multiple different kinds of classes. This allows the sending objects to invoke behaviors and to delegate the implementation of those behaviors to the receiving object. A method in [[Java (programming language)|Java]] programming sets the behavior of a class object. For example, an object can send an <code>area</code> message to another object and the appropriate formula is invoked whether the receiving object is a <code>rectangle</code>, <code>circle</code>, <code>triangle</code>, etc.
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.
 
Methods also provide the interface that other classes use to access and modify the properties of an object; this is known as [[Encapsulation (computer programming)|''encapsulation'']]. Encapsulation and overriding are the two primary distinguishing features between methods and procedure calls.<ref>{{cite web|title=What is an Object?|url=http://docs.oracle.com/javase/tutorial/java/concepts/object.html|work=oracle.com|publisher=Oracle Corporation|access-date=13 December 2013}}</ref>
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]] of a particular [[object (computer science)|object]]. In [[Java programming language|Java]] and [[C Plus Plus|C++]], '''constructors''' 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 to the object they belong to, so that they can access the data associated with the instance that they are called upon.
 
==Overriding and overloading==
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>.
[[Method overriding]] and [[Function overloading|overloading]] are two of the most significant ways that a method differs from a conventional procedure or function call. Overriding refers to a subclass redefining the implementation of a method of its superclass. For example, <code>findArea</code> may be a method defined on a shape class,<ref name=":0" /> <code>triangle</code>, etc. would each define the appropriate formula to calculate their area. The idea is to look at objects as "black boxes" so that changes to the internals of the object can be made with minimal impact on the other objects that use it. This is known as encapsulation and is meant to make code easier to maintain and re-use.
 
Method overloading, on the other hand, refers to differentiating the code used to handle a message based on the parameters of the method. If one views the receiving object as the first parameter in any method then overriding is just a special case of overloading where the selection is based only on the first argument. The following simple Java example illustrates the difference:
An '''abstract method''' is a method which has no [[implementation]]. It is used to make a place-holder to be overridden later.
 
==Accessor, mutator and manager methods==
An '''accessor method''' is a kind of 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, 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 "getBalance()" accessor method to retrieve the current balance (rather than directly accessing the balance data fields), then later revisions of the same code can implement a more complex mechanism balance retrieval (say, a database fetch) without the dependent code needing to be changed.
[[Accessor method]]s are used to read the data values of an object. Mutator methods are used to modify the data of an object. Manager methods are used to initialize and destroy objects of a class, e.g. constructors and destructors.
 
These methods provide an [[abstraction layer]] that facilitates [[Encapsulation (object-oriented programming)|encapsulation]] and [[Modularity (programming)|modularity]]. For example, if a bank-account class provides a <code>getBalance()</code> accessor method to retrieve the current [[Balance (accounting)|balance]] (rather than directly accessing the balance data fields), then later [[revision control|revisions]] of the same code can implement a more complex mechanism for balance retrieval (e.g., a [[database]] fetch), without the dependent code needing to be changed. The concepts of encapsulation and modularity are not unique to object-oriented programming. Indeed, in many ways the object-oriented approach is simply the logical extension of previous paradigms such as [[abstract data types]] and [[structured programming]].<ref>{{cite book|last=Meyer|first=Bertrand|title=Object-Oriented Software Construction|year=1988|publisher=Prentice Hall International Series in Computer Science|___location=Cambridge|isbn=0-13-629049-3|pages=52–54}}</ref>
An accessor method that changes the state of an object is sometimes especially called '''mutator''' or '''update method'''. Objects with such a method are considered [[immutable objects|mutable objects]].
 
===Constructors===
{{Main|Constructor (computer science)}}
 
A [[Constructor (computer science)|''constructor'']] is a method that is called at the beginning of an object's lifetime to create and initialize the object, a process called [[object creation|construction]] (or ''instantiation''). Initialization may include an acquisition of resources. Constructors may have parameters but usually do not return values in most languages. See the following example in Java:
 
<syntaxhighlight lang="java">
public class Main {
String _name;
int _roll;
 
Main(String name, int roll) { // constructor method
this._name = name;
this._roll = roll;
}
}
</syntaxhighlight>
 
===Destructor===
{{Main|Destructor (computer science)}}
A ''[[Destructor (computer science)|Destructor]]'' is a method that is called automatically at the end of an object's lifetime, a process called [[object lifetime|Destruction]]. Destruction in most languages does not allow destructor method arguments nor return values. Destructors can be implemented so as to perform cleanup chores and other tasks at object destruction.
 
====Finalizers====
In [[Garbage collection (computer science)|garbage-collected]] languages, such as [[Java (programming language)|Java]],<ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|26, 29}} [[C Sharp (programming language)|C#]],<ref name=Albahari>{{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |publisher= O'Reilly |isbn= 978-1-098-12195-2}}</ref>{{rp|208-209}} and [[Python (programming language)|Python]], destructors are known as ''[[finalizer]]s''. They have a similar purpose and function to destructors, but because of the differences between languages that utilize garbage-collection and languages with [[manual memory management]], the sequence in which they are called is different.
 
==Abstract methods==
An '''abstract method''' is one with only a [[method signature|signature]] and no [[method body|implementation body]]. It is often used to specify that a subclass must provide an implementation of the method, as in an [[Class (computer programming)#Abstract and concrete|abstract class]]. Abstract methods are used to specify [[Interface (computing)|interfaces]] in some programming languages.<ref>{{cite web|title=Abstract Methods and Classes|url=http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html|website=oracle.com|publisher=Oracle Java Documentation|access-date=11 December 2014}}</ref>
 
===Example===
[[File:UML abstract methods.svg]]
 
The following [[Java (programming language)|Java]] code shows an abstract class that needs to be extended:
 
<syntaxhighlight lang="java">
abstract class Shape {
abstract int area(int h, int w); // abstract method signature
}
</syntaxhighlight>
The following subclass extends the main class:
 
<syntaxhighlight lang="java">
public class Rectangle extends Shape {
@Override
int area(int h, int w) {
return h * w;
}
}
</syntaxhighlight>
 
===Reabstraction===
If a subclass provides an implementation for an abstract method, another subclass can make it abstract again. This is called ''reabstraction''.
 
In practice, this is rarely used.
 
====Example====
In C#, a virtual method can be overridden with an abstract method. (This also applies to Java, where all non-private methods are virtual.)
<syntaxhighlight lang="csharp">
class IA
{
public virtual void M() { }
}
abstract class IB : IA
{
public override abstract void M(); // allowed
}
</syntaxhighlight>
 
Interfaces' default methods can also be reabstracted, requiring subclasses to implement them. (This also applies to Java.)
<syntaxhighlight lang="csharp">
interface IA
{
void M() { }
}
interface IB : IA
{
abstract void IA.M();
}
class C : IB { } // error: class 'C' does not implement 'IA.M'.
</syntaxhighlight>
 
==Class methods==
Class methods are methods that are called on a [[Class (computer programming)|class]] rather than an instance. They are typically used as part of an object [[meta-model]]. I.e, for each class, defined an instance of the class object in the meta-model is created. [[Meta-object protocol|Meta-model protocols]] allow classes to be created and deleted. In this sense, they provide the same functionality as constructors and destructors described above. But in some languages such as the [[Common Lisp Object System|Common Lisp Object System (CLOS)]] the meta-model allows the developer to dynamically alter the [[object model]] at run time: e.g., to create new classes, redefine the class hierarchy, modify properties, etc.
 
==Special methods==
Special methods are very language-specific and a language may support none, some, or all of the special methods defined here. A language's [[compiler]] may automatically generate default special methods or a programmer may be allowed to optionally define special methods. Most special methods cannot be directly called, but rather the compiler generates code to call them at appropriate times.
 
===Static methods===
{{see also|Static member function}}
Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to [[static variable]]s in that sense. An example would be a static method to sum the values of all the variables of every instance of a class. For example, if there were a <code>Product</code> class it might have a static method to compute the average price of all products.
 
A static method can be invoked even if no instances of the class exist yet. Static methods are called "static" because they are resolved at [[compile time]] based on the class they are called on and not dynamically as in the case with instance methods, which are resolved polymorphically based on the runtime type of the object.
 
====Examples====
=====In Java=====
In Java, a commonly used static method is:
Math.max(double a, double b)
This static method has no owning object and does not run on an instance. It receives all information from its arguments.<ref name=":0">{{Cite book|title = Clean Code: A Handbook of Agile Software Craftsmanship|last = Martin|first = Robert C.|publisher = Prentice Hall|year = 2009|isbn = 978-0-13-235088-4|pages = 296|author-link = Robert Cecil Martin}}</ref>
 
===Copy-assignment operators===
Copy-assignment operators define actions to be performed by the compiler when a class object is assigned to a class object of the same type.
 
===Operator methods===
Operator methods [[Operator overloading|define or redefine operator symbols]] and define the operations to be performed with the symbol and the associated method parameters. C++ example:
<syntaxhighlight lang="cpp">
#include <string>
 
class Data {
public:
bool operator<(const Data& data) const { return roll_ < data.roll_; }
bool operator==(const Data& data) const {
return name_ == data.name_ && roll_ == data.roll_;
}
 
private:
std::string name_;
int roll_;
};
</syntaxhighlight>
 
==Member functions in C++==
Some procedural languages were extended with object-oriented capabilities to leverage the large skill sets and legacy code for those languages but still provide the benefits of object-oriented development. Perhaps the most well-known example is [[C++]], an object-oriented extension of the [[C (programming language)|C]] programming language. Due to the design requirements to add the object-oriented paradigm on to an existing procedural language, message passing in C++ has some unique capabilities and terminologies. For example, in C++ a method is known as a ''member function''. C++ also has the concept of [[virtual function]]s which are member functions that can be [[Method overriding|overridden]] in [[derived class]]es and allow for [[dynamic dispatch]].
 
===Virtual functions===
''[[Virtual function]]s'' are the means by which a C++ class can achieve polymorphic behavior. ''Non-virtual member functions'', or ''regular methods'', are those that do not participate in [[polymorphism (computer science)|polymorphism]].
 
C++ Example:
<syntaxhighlight lang="cpp">
#include <iostream>
#include <memory>
 
class Super {
public:
virtual ~Super() = default;
 
virtual void IAm() { std::cout << "I'm the super class!\n"; }
};
 
class Sub : public Super {
public:
void IAm() override { std::cout << "I'm the subclass!\n"; }
};
 
int main() {
std::unique_ptr<Super> inst1 = std::make_unique<Super>();
std::unique_ptr<Super> inst2 = std::make_unique<Sub>();
 
inst1->IAm(); // Calls |Super::IAm|.
inst2->IAm(); // Calls |Sub::IAm|.
}
</syntaxhighlight>
 
==See also==
* [[Property (programming)]]
* [[Remote method invocation]]
* [[Subroutine]], also called subprogram, routine, procedure or function
 
== Notes ==
{{reflist}}
 
== References ==
{{refbegin}}
*{{cite book|url=https://books.google.com/books?id=DnsM0WD-6iMC&pg=PA131|title=C++ and Object-oriented Programming Paradigm|last=JANA|first=DEBASISH|date=1 January 2005|publisher=PHI Learning Pvt. Ltd.|isbn=978-81-203-2871-6}}
*{{cite book|url=https://books.google.com/books?id=ZLzt5WtsdzIC&pg=PA50|title=Object-Oriented Programming: Fundamentals And Applications|last=Sengupta|first=Probal|date=1 August 2004|publisher=PHI Learning Pvt. Ltd.|isbn=978-81-203-1258-6}}
*{{cite book|url=https://books.google.com/books?id=Miq73i_J1i4C&pg=PA36|title=Object-oriented Programming: Using C++ for Engineering and Technology|last=Svenk|first=Goran|publisher=Cengage Learning|year=2003|isbn=0-7668-3894-3}}
*{{cite book|url=https://books.google.com/books?id=WCHZAgAAQBAJ&pg=PA74|title=Object Oriented Programming with C++|publisher=Tata McGraw-Hill Education|year=2013|isbn=978-1-259-02993-6|author=Balagurusamy}}
*{{cite book|url=https://books.google.com/books?id=-yhuY0Wg_QcC&pg=PA181|title=A Complete Guide to Programming in C++|last2=Prinz|first2=Peter|publisher=Jones & Bartlett Learning|year=2002|isbn=978-0-7637-1817-6|last1=Kirch-Prinz|first1=Ulla}}
*{{cite book|url=https://books.google.com/books?id=1F6ipojt7DcC&pg=PA79|title=Creating Games in C++: A Step-by-step Guide|last=Conger|first=David|publisher=New Riders|year=2006|isbn=978-0-7357-1434-2}}
*{{cite book|url=https://books.google.com/books?id=fgGLZ7WYxCMC&pg=PA97|title=The Advanced C++ Book|last=Skinner|first=M. T.|publisher=Silicon Press|year=1992|isbn=978-0-929306-10-0}}
*{{cite book|url=https://books.google.com/books?id=NXVkcCjPblcC&pg=PA18|title=Linux Kernel Development|date=1 September 2005|publisher=Pearson Education|isbn=978-81-7758-910-8|author=Love}}
*{{cite book|url=https://books.google.com/books?id=fxUVrhjD4k0C&pg=PA78|title=OBJECT-ORIENTED PROGRAMMING USING C++|last2=JAGADEV|first2=ALOK KUMAR|last3=RATH|first3=AMIYA KUMAR|date=8 May 2007|publisher=PHI Learning Pvt. Ltd.|isbn=978-81-203-3085-6|last1=DEHURI|first1=SATCHIDANANDA}}
{{refend}}
 
{{DEFAULTSORT:Method (Computer Science)}}
<!--Categories-->
[[Category:Method (computer programming)| ]]
[[Category:Articles with example C++ code]]
 
[[sv:Funktion (programmering)#Metod]]