Method (computer programming): Difference between revisions

Content deleted Content added
m linking
Link suggestions feature: 2 links added.
 
(43 intermediate revisions by 28 users not shown)
Line 1:
{{short description|Computer function or subroutineFunction that is tied to a particular instance or class}}
 
A '''method''' in [[object-oriented programming]] (OOP) is a [[Procedure (computer science)|procedure]] associated with aan [[MessageObject passing(computer science)|messageobject]], and angenerally also a [[ObjectMessage (computer science)passing|objectmessage]]. An object consists of ''state data'' and ''behavior''; these comprisecompose an [[Interface (computingobject-oriented programming)|''interface'']], which specifies how the object may be utilizedused. byA anymethod ofis itsa various consumers.<ref name="consumerdef001a">Consumersbehavior of an object mayparametrized consistby of various kinds of elements, such as other programs, remote computer systems, or computer programmers who wish to utilize the object as part of their owna programsuser.</ref>
 
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.
Line 10:
 
==Overriding and overloading==
[[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:
Line 20:
 
===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:
 
Line 34 ⟶ 36:
</syntaxhighlight>
 
===DestructorsDestructor===
{{Main|Destructor (computer science)}}
A ''[[Destructor (computer science)|destructorDestructor]]'' is a method that is called automatically at the end of an object's lifetime, a process called [[object lifetime|destructionDestruction]]. Destruction in most languages does not allow destructor method arguments nor return values. DestructionDestructors 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:
 
Line 94 ⟶ 99:
 
==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>
 
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.
 
===Copy-assignment operators===
Line 171 ⟶ 179:
== References ==
{{refbegin}}
*{{cite book|url=https://books.google.com/books?id=DnsM0WD-6iMC&pg=PA131|title=C++ ANDand OBJECTObject-ORIENTEDoriented PROGRAMMINGProgramming PARADIGMParadigm|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}}