HOME

TheInfoList



OR:

A method in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
(OOP) is a procedure associated with a
message A message is a discrete unit of communication intended by the source for consumption by some recipient or group of recipients. A message may be delivered by various means, including courier, telegraphy, carrier pigeon and electronic bus. A ...
and an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of its various consumers. A method is a behavior of an object parametrized by a consumer. Data is represented as
properties Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property. Property may also refer to: Mathematics * Property (mathematics) Philosophy and science * Property (philosophy), in philosophy and ...
of the object, and behaviors are represented as methods. For example, a Window object could have methods such as open and close, while its state (whether it is open or closed at any given point in time) would be a property. In
class-based programming Class-based programming, or more commonly class-orientation, is a style of object-oriented programming (OOP) in which inheritance occurs via defining ''classes'' of objects, instead of inheritance occurring via the objects alone (compare prototy ...
, methods are defined within a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
, and objects are instances of a given class. One of the most important capabilities that a method provides is ''
method overriding Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to ...
'' - the same name (e.g., area) 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 Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
programming sets the behavior of a class object. For example, an object can send an area message to another object and the appropriate formula is invoked whether the receiving object is a rectangle, circle, triangle, etc. Methods also provide the interface that other classes use to access and modify the properties of an object; this is known as ''encapsulation''. Encapsulation and overriding are the two primary distinguishing features between methods and procedure calls.


Overriding and overloading

Method overriding Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to ...
and 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, findArea may be a method defined on a shape class, triangle, 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:


Accessor, mutator and manager methods

Accessor method 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 (together also known as accessors), which returns the value of the priva ...
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 In computing, an abstraction layer or abstraction level is a way of hiding the working details of a subsystem. Examples of software models that use layers of abstraction include the OSI model for network protocols, OpenGL, and other graphics libra ...
that facilitates encapsulation and
modularity Broadly speaking, modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a sy ...
. For example, if a bank-account class provides a getBalance() accessor method to retrieve the current
balance Balance or balancing may refer to: Common meanings * Balance (ability) in biomechanics * Balance (accounting) * Balance or weighing scale * Balance as in equality or equilibrium Arts and entertainment Film * ''Balance'' (1983 film), a Bulgarian ...
(rather than directly accessing the balance data fields), then later
revisions Revision is the process of revising. More specifically, it may refer to: * Update, a modification of software or a database * Revision control, the management of changes to sets of computer files * '' ReVisions'', a 2004 anthology of alternate h ...
of the same code can implement a more complex mechanism for balance retrieval (e.g., a
database In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases sp ...
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 In computer science, an abstract data type (ADT) is a mathematical model for data types. An abstract data type is defined by its behavior (semantics) from the point of view of a ''user'', of the data, specifically in terms of possible values, pos ...
and
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
.


Constructors

A ''constructor'' is a method that is called at the beginning of an object's lifetime to create and initialize the object, a process called
construction Construction is a general term meaning the art and science to form objects, systems, or organizations,"Construction" def. 1.a. 1.b. and 1.c. ''Oxford English Dictionary'' Second Edition on CD-ROM (v. 4.0) Oxford University Press 2009 and com ...
(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: public class Main


Destructors

A '' destructor'' is a method that is called automatically at the end of an object's lifetime, a process called
destruction Destruction may refer to: Concepts * Destruktion, a term from the philosophy of Martin Heidegger * Destructive narcissism, a pathological form of narcissism * Self-destructive behaviour, a widely used phrase that ''conceptualises'' certain kind ...
. Destruction in most languages does not allow destructor method arguments nor return values. Destruction can be implemented so as to perform cleanup chores and other tasks at object destruction.


Finalizers

In garbage-collected languages, such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, C#, and
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, destructors are known as ''
finalizer In computer science, a finalizer or finalize method is a special method that performs finalization, generally some form of cleanup. A finalizer is executed during object destruction, prior to the object being deallocated, and is complementary to ...
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
signature A signature (; from la, signare, "to sign") is a handwritten (and often stylized) depiction of someone's name, nickname, or even a simple "X" or other mark that a person writes on documents as a proof of identity and intent. The writer of a ...
and no implementation body. It is often used to specify that a subclass must provide an implementation of the method. Abstract methods are used to specify
interfaces Interface or interfacing may refer to: Academic journals * Interface (journal), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
in some programming languages.


Example

The following
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
code shows an abstract class that needs to be extended: abstract class Shape The following subclass extends the main class: public class Rectangle extends Shape


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.) class IA abstract class IB : IA Interfaces' default methods can also be reabstracted, requiring subclasses to implement them. (This also applies to Java.) interface IA interface IB : IA class C : IB // error: class 'C' does not implement 'IA.M'.


Class methods

Class methods are methods that are called on a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
rather than an instance. They are typically used as part of an object
meta-model A metamodel or surrogate model is a model of a model, and metamodeling is the process of generating such metamodels. Thus metamodeling or meta-modeling is the analysis, construction and development of the frames, rules, constraints, models and ...
. I.e, for each class, defined an instance of the class object in the meta-model is created. 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 (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

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 In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
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 Product class it might have a static method to compute the average price of all products. 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. 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 In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
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

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 define or redefine operator symbols and define the operations to be performed with the symbol and the associated method parameters. C++ example: #include class Data ;


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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, an object-oriented extension of the 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 In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
s which are member functions that can be overridden in
derived class In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
es and allow for
dynamic dispatch In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
.


Virtual functions

''
Virtual function In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
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. C++ Example: #include #include class Super ; class Sub : public Super ; int main()


See also

*
Property (programming) A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method. The syntax for reading and writing of properties is like for fields, but prop ...
*
Remote method invocation In a distributed computing environment, distributed object communication realizes communication between distributed objects. The main role is to allow objects to access data and invoke methods on remote objects (objects residing in non-local memory ...
*
Subroutine In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
, also called subprogram, routine, procedure or function


Notes


References

* * * * * * * * * {{DEFAULTSORT:Method (Computer Science) Articles with example C++ code sv:Funktion (programmering)#Metod