Teknik Informatika    
   
Daftar Isi
(Sebelumnya) MetaTeamMetric prefix (Berikutnya)

Method (computer programming)

In object-oriented programming, a method is a subroutine (or procedure) associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance.[1] The association between class and method is called binding. A method associated with a class is said to be bound to the class. Methods can be bound to a class at compile time (static binding) or to an object at runtime (dynamic binding).[2]

Contents

Example

The following Java code defines a method "rectangle" in the class "main" that can find area of a rectangle.

public class Main{ int rectangle(int h, int w) { return h*w; }}

The following C++ code defines a methods "Input" and "Display".

#include <iostream>using namespace std; struct goods{ char name[40]; float price; static int percent; void input() { cout << "Good's name: "; cin >> name; cout << "Price: "; cin >> price; } void display() { cout << "\n" << name; cout << ", Final price with tax: "; cout << long(price * (1.0 + goods::percent * 0.01)); cout << "\n"; }}; int goods::percent = 20; int main(){ goods a[3]; for(int i = 0; i <= 2; i++) { a[i].input(); } for(int i = 0; i <= 2; i++) { a[i].display(); } return 0;}
#include <stdio.h>#include <stdlib.h> using namespace std; int main(){ int n,j,i; float **matr; float *mass; printf("Enter size of sqare matrix n:"); scanf("%d", &n); mass = (float *) malloc(n*sizeof(float)); if (mass == NULL){ puts("Dynamic structure don't created!"); return 0; } matr = (float **) malloc(sizeof(float *)*n); if (matr == NULL) { puts("Dynamic structure don't created!"); return 0; } for (i = 0; i < n; i++){ matr[i] = (float *) malloc(sizeof(float)*n); if(matr[i] == NULL){ puts("Dynamic structure don't created!"); return 0; } for (j = 0; j<n; j++) matr[i][j] = rand() % 100; }   for( i = 0; i<n; i++){ mass[i] = 0; for(j = 0; j<n; j++) mass[i]+=matr[i][j]; } for(i=0; i<n; i++){ for(j=0; j<n; j++) printf("\t%6.2f", matr[i][j]); printf("\n"); } for (i=0; i<n; i++) printf("\n sum of %d string %8.2f", i, mass[i]); for (i=0; i<n; i++) free(matr[i]); free(matr); free(mass);}

Abstract methods

An abstract method is one with only a signature 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 in some computer languages.[citation needed]

Example

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

abstract class Main{ abstract int rectangle(int h, int w); // abstract method signature}

The following subclass extends the main class:

public class Main2 extends Main{ @Override int rectangle(int h, int w) { return h*w; } }

Accessor and mutator methods

An 'accessor' method is a method that is usually small, simple and provides the sole means for the state of an object to be accessed (retrieved) from other parts of a program.

Although this introduces a new dependency, as stated above, use of methods is preferred, in the object-oriented paradigm, to directly accessing state data - because those methods 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 for balance retrieval (say, a database fetch), without the dependent code needing to be changed (However, this often claimed advantage is not unique to object oriented programming, and was earlier implemented - when desirable in critical systems - through conventional modular programming with optional run-time, system-wide locking mechanisms, in the imperative/procedural paradigms)

To compare the value of two data items, two accessor-method calls are normally required before a comparison can take place between the retrieved primitive data type values. Comparator methods are required to compare entire objects for equality. This contrasts with a direct comparison in non-OOP paradigms. An update, modifier, or mutator method, is an accessor method that changes the state of an object. Objects that provide such methods are considered mutable objects.

Class methods

Class methods are methods that are called on a class (compare this to class instance methods, or object methods). Its meaning may vary depending on the programming language:

  • In some languages (e.g. C++, Java), class methods are synonymous with static methods (see section below), which are called with a known class name at compile-time. this cannot be used in static methods.
  • In some other languages (e.g. Smalltalk, Ruby, Objective-C), class methods are methods that are called on a class object, which can be computed at runtime, there being no difference between calling a method on a regular object or a class object; thus both instance and class methods are resolved dynamically, and there are no "static" methods. Notably, in these class methods, this refers to the class object.
  • Some languages have both. For example, in Python, one can create class methods and static methods using the classmethod and staticmethod decorators, respectively. The former has access to this (i.e. the instance object, conventionally known as self), while the latter does not.

Conversion operator methods

A conversion operator provides a means for the compiler to implicitly (performed by the compiler automatically when appropriate) provide an object of a type other than the type of the class object.

Hook methods

Hook methods are defined in abstract classes and called from a template method. Hooks are used as placeholders that can be supplied by the component's client in a concrete derived class.[3][4] Here is a Java example:[5]

/** */public abstract class Beverage implements Beveragelike { /** * Adds condiments to the beverage */ public abstract void addCondiments(); /** * Hook method that determines whether the customer wants condiments * or not. Can be overridden. * @return true, if the customer wants condiments, and false otherwise. */ public boolean customerWantsCondiments() { return true; } /** * Prepares the beverage according to this recipe. */ public final void prepareRecipe() { // … if (customerWantsCondiments()) { addCondiments(); } }}

Overloaded methods

Overloaded methods are those that appear to have the same name, but that have different formal parameter types (or result value type, if the language supports overloading on result type). The "real name" of the method is made up by concatenating the identifier used to name the method with an encoding of the types, so this works only for languages in which the types are statically known. Overloading is generally confusing; it is better practice to simply come up with more meaningful names for ones methods, that is, names that explain the role of the parameters.[6] For example in the following C++, class geometry have two method named "area". But their parameter list is different which distinguish the methods. Many other languages provide this feature.

#include<iostream>using namespace std;class geometry{ public: static double area(double h, double w) { return h*w; } static double area(double r) { return r*r*3.14; } };int main(){ double rectangle_area = geometry().area(3,4); double circle_area = geometry().area(5); cout << rectangle_area << endl; cout << circle_area << endl; return 0;}

Overridden methods

Overridden methods are those that are redefined in a subclass and hide methods of a superclass. The new method can use the previous definition through a special mechanism, for example, the super keyword in Smalltalk and Java. Some people confuse overriding with overloaded methods, but they are really quite different; the main difference is that the choice of method from a set of overriding methods is made according to the class of the receiver of the method request, whereas the name of an overloaded method is constructed according to the static types of the arguments to the method request. Another difference is that an overriding method must be declared in a subclass of the class that declared the overridden method, while several overloadings of a method name can be declared in the same class.[7] Look at following example in Java:

public class class1{ int f(int x) { return x+3; }} public class class2 extends class1{ @Override int f(int x) // overriding { return x*x; } int f(int x, int y) // overloading { return x*y; }}

[8]

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. The syntax for definition and calling (i.e., when a special method can be called) of special methods varies amongst programming languages.[citation needed]

Constructors

A constructor is a class method that is called automatically at the beginning of an object's lifetime to initialize the object, a process called construction (or instantiation). Initialization may include acquisition of resources. A language may provide a means to control whether a constructor can be called implicitly (by the compiler) or only explicitly (by the programmer). Constructors may have parameters but usually do not return values in most languages. See the following example in Java:

public class Main{ String name; int roll; Main(String _name, int _roll) { //constructor method (this).name = _name; (this).roll = _roll; } }

Destruction

A destructor is a class method that is called automatically at the end of an object's lifetime, a process called destruction. Destruction in most languages does not allow destructor method arguments nor return values. (In some languages (ref required), a destructor can return a value which can then be used to obtain a public representation (transfer encoding) of an instance of a class and simultaneously destroy the copy of the instance stored in current thread's memory). Destruction can be implemented so as to perform clean up chores and other tasks at object destruction.

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:

class data{ public: string name; int roll; bool operator < (const data& p) const { return roll < p.roll; } bool operator == (const data& p) const { return (name == p.name) and (roll == p.roll); }};

Some programming languages don't support operator methods as they might create confusion. For details read: Operator overloading.

Static methods

Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance. A static method is distinguished in some programming languages with the static keyword placed somewhere in the method's signature. Static methods are called "static" because they are resolved statically (i.e. at compile time) in statically typed languages 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. Therefore, static methods cannot be overridden.[9]

Virtual methods

Virtual methods are the means by which a class object can achieve polymorphic behavior. Non-virtual methods, or regular methods, are those which do not participate in polymorphism.[10]

C++ Example:

class Super{ public: virtual void iAm() { std::cout << "I'm the super class!" << std::endl; }} class Sub:public Super{ public: void iAm() { std::cout << "I'm the subclass!" << std::endl; }} Super *inst1 = new Super();Super *inst2 = new Sub(); inst1->iAm(); // calls Super.iAm()inst2->iAm(); // calls Sub.iAm()

References

  1. ^ Mark Slagell (2008). "Methods". http://www.rubyist.net/~slagell/ruby/: Ruby User's Guide. http://www.rubyist.net/~slagell/ruby/ methods.html. Retrieved 2011-08-12. "What is a method? In OO programming, we don't think of operating on data directly from outside an object; rather, objects have some understanding of how to operate on themselves (when asked nicely to do so). You might say we pass messages to an object, and those messages will generally elicit some kind of an action or meaningful reply. This ought to happen without our necessarily knowing or caring how the object really works inside. The tasks we are allowed to ask an object to perform (or equivalently, the messages it understands) are that object's methods."
  2. ^ "OOPS Interview Questions: 17. What is Binding?". http://www.tolmol.com/: TOLMOL Beta. http://www.tolmol.com/gp/java-intervi ew-questionstips/oops-interview-quest ions.htm. Retrieved 2011-08-12. "Binding denotes association of a name with a class."
  3. ^ "Template Method Design Pattern". Source Making - teaching IT professional. http://sourcemaking.com/design_patter ns/template_method. Retrieved 2012-09-12. "The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent “hooks”, or “placeholders”, that can, or must, be supplied by the component’s client in a concrete derived class."
  4. ^ "Hook Method". Cunningham & Cunningham, Inc.. 2002-08-27. Archived from the original on 2002-08-27. http://c2.com/cgi/wiki?HookMethod. Retrieved 2012-09-12.
  5. ^ Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike. ed (paperback). Head First Design Patterns. 1. O'REILLY. p. 293. ISBN 978-0-596-00712-6. http://it-ebooks.info/book/252/. Retrieved 2012-09-12.
  6. ^ John Suzuki (2000-02-18). "What is an overloaded method?". http://www.jguru.com/: j Guru. http://www.jguru.com/faq/view.jsp?EID =15565. Retrieved 2011-08-12. "Overloaded methods are multiple methods in the same class that share the same name but have different parameter lists. Overloaded methods cannot have the same parameter lists with different return types."
  7. ^ http://www.codeproject.com/Articles/1 6407/METHOD-Overload-Vs-Overriding
  8. ^ Anandvijayakumar. "What is an overridden method and overriding a method?". http://www.answers.com/: Answers.com. http://wiki.answers.com/Q/What_is_an_ overridden_method_and_overriding_a_me thod. Retrieved 2011-08-12. "Assuming class A has a method named getXXX() and class B is a sub class of class A. Now, if we write a method with the same name getXXX() in class B, with exactly the same signature as class A, it is called overriding a method."
  9. ^ http://www.javabeat.net/qna/49-can-we -override-static-methods-what-is-meth o/
  10. ^ Alexis Angelidis. "What is a virtual method?". http://www.cs.otago.ac.nz/postgrads/a lexis/tutorial/: Online C++ FAQ/Tutorial and Advanced Questions. http://www.cs.otago.ac.nz/postgrads/a lexis/tutorial/node37.html. Retrieved 2011-08-12. "A virtual method in a parent allows children to have a different implementation for it. A pure virtual method in a parent forces children to have an implementation for it (interface in Java). A class with a pure virtual method is called virtual."

See also

(Sebelumnya) MetaTeamMetric prefix (Berikutnya)