Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Method (computer programming)

From Wikipedia, the free encyclopedia
(Redirected fromAbstract method)
Function that is tied to a particular instance or class

Amethod inobject-oriented programming (OOP) is aprocedure associated with anobject, and generally also amessage. An object consists ofstate data andbehavior; these compose aninterface, which specifies how the object may be used. A method is a behavior of an object parametrized by a user.

Data is represented asproperties of the object, and behaviors are represented as methods. For example, aWindow object could have methods such asopen andclose, while its state (whether it is open or closed at any given point in time) would be a property.

Inclass-based programming, methods are defined within aclass, and objects areinstances of a given class. One of the most important capabilities that a method provides ismethod overriding - 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 inJava programming sets the behavior of a class object. For example, an object can send anarea message to another object and the appropriate formula is invoked whether the receiving object is arectangle,circle,triangle, etc.

Methods also provide the interface that other classes use to access and modify the properties of an object; this is known asencapsulation. Encapsulation and overriding are the two primary distinguishing features between methods and procedure calls.[1]

Overriding and overloading

[edit]

Method overriding andoverloading 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,[2]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

[edit]

Accessor methods 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 anabstraction layer that facilitatesencapsulation andmodularity. For example, if a bank-account class provides agetBalance() accessor method to retrieve the currentbalance (rather than directly accessing the balance data fields), then laterrevisions of the same code can implement a more complex mechanism for balance retrieval (e.g., adatabase 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 asabstract data types andstructured programming.[3]

Constructors

[edit]
Main article:Constructor (computer science)

Aconstructor is a method that is called at the beginning of an object's lifetime to create and initialize the object, a process calledconstruction (orinstantiation). 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:

publicclassMain{String_name;int_roll;Main(Stringname,introll){// constructor methodthis._name=name;this._roll=roll;}}

Destructor

[edit]
Main article:Destructor (computer science)

ADestructor is a method that is called automatically at the end of an object's lifetime, a process calledDestruction. 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

[edit]

Ingarbage-collected languages, such asJava,[4]: 26, 29 C#,[5]: 208–209  andPython, destructors are known asfinalizers. 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

[edit]

Anabstract method is one with only asignature and noimplementation body. It is often used to specify that a subclass must provide an implementation of the method, as in anabstract class. Abstract methods are used to specifyinterfaces in some programming languages.[6]

Example

[edit]

The followingJava code shows an abstract class that needs to be extended:

abstractclassShape{abstractintarea(inth,intw);// abstract method signature}

The following subclass extends the main class:

publicclassRectangleextendsShape{@Overrideintarea(inth,intw){returnh*w;}}

Reabstraction

[edit]

If a subclass provides an implementation for an abstract method, another subclass can make it abstract again. This is calledreabstraction.

In practice, this is rarely used.

Example

[edit]

In C#, a virtual method can be overridden with an abstract method. (This also applies to Java, where all non-private methods are virtual.)

classIA{publicvirtualvoidM(){}}abstractclassIB:IA{publicoverrideabstractvoidM();// allowed}

Interfaces' default methods can also be reabstracted, requiring subclasses to implement them. (This also applies to Java.)

interfaceIA{voidM(){}}interfaceIB:IA{abstractvoidIA.M();}classC:IB{}// error: class 'C' does not implement 'IA.M'.

Class methods

[edit]

Class methods are methods that are called on aclass rather than an instance. They are typically used as part of an objectmeta-model. 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 theCommon Lisp Object System (CLOS) the meta-model allows the developer to dynamically alter theobject model at run time: e.g., to create new classes, redefine the class hierarchy, modify properties, etc.

Special methods

[edit]

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

[edit]
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 tostatic variables 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 aProduct 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 atcompile 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

[edit]
In Java
[edit]

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.[2]

Copy-assignment operators

[edit]

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

[edit]

Operator methodsdefine or redefine operator symbols and define the operations to be performed with the symbol and the associated method parameters. C++ example:

#include<string>classData{public:booloperator<(constData&data)const{returnroll_<data.roll_;}booloperator==(constData&data)const{returnname_==data.name_&&roll_==data.roll_;}private:std::stringname_;introll_;};

Member functions in C++

[edit]

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 isC++, an object-oriented extension of theC 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 amember function. C++ also has the concept ofvirtual functions which are member functions that can beoverridden inderived classes and allow fordynamic dispatch.

Virtual functions

[edit]

Virtual functions are the means by which a C++ class can achieve polymorphic behavior.Non-virtual member functions, orregular methods, are those that do not participate inpolymorphism.

C++ Example:

#include<iostream>#include<memory>classSuper{public:virtual~Super()=default;virtualvoidIAm(){std::cout<<"I'm the super class!\n";}};classSub:publicSuper{public:voidIAm()override{std::cout<<"I'm the subclass!\n";}};intmain(){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|.}

See also

[edit]

Notes

[edit]
  1. ^"What is an Object?".oracle.com. Oracle Corporation. Retrieved13 December 2013.
  2. ^abMartin, Robert C. (2009).Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall. p. 296.ISBN 978-0-13-235088-4.
  3. ^Meyer, Bertrand (1988).Object-Oriented Software Construction. Cambridge: Prentice Hall International Series in Computer Science. pp. 52–54.ISBN 0-13-629049-3.
  4. ^Bloch, Joshua (2018)."Effective Java: Programming Language Guide" (third ed.). Addison-Wesley.ISBN 978-0134685991.
  5. ^Albahari, Joseph.C# 10 in a Nutshell. O'Reilly.ISBN 978-1-098-12195-2.
  6. ^"Abstract Methods and Classes".oracle.com. Oracle Java Documentation. Retrieved11 December 2014.

References

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Method_(computer_programming)&oldid=1265937912#Abstract_methods"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp