메서드 (컴퓨터 프로그래밍)

객체와 관련된 함수이자 클래스가 갖고 있는 기능

메서드(method) 또는 멤버 함수객체 지향 프로그래밍에서 객체와 관련된 서브 루틴 (또는 함수)이자 클래스가 갖고 있는 기능이다. 데이터와 멤버 변수에 대한 접근 권한을 갖는다.

클래스 기반 언어에서 클래스 내부에 정의되어 있다. 메서드는 프로그램이 실행되고 있을 때 클래스에서 생성된 인스턴스와 관련된 동작을 정의한다. 메서드는 런타임 중에 클래스 인스턴스 (또는 클래스 객체)에 저장되어 있는 데이터에 접근할 수 있는 특수 속성을 가지고 있다.[1] 바인딩은 클래스와 메서드 간의 연관관계를 말한다. 클래스와 관련된 메서드는 클래스에 바인딩 할 수 있다. 메서드는 컴파일 타임 (정적 바인딩) 또는 런타임 (동적 바인딩)에 클래스에 바인딩 할 수 있다.[2]

예제 편집

아래의 자바 코드는 사각형의 넓이를 계산하는 "rectangle" 메서드를 정의한 것이다.

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

아래의 C++ 코드는 입력과 출력 메서드를 정의한 것이다.

#include <iostream>
#include <string>
#include <array>

struct goods
{
	std::string name;
	float price;
	static int percent;
	void input()
	{
		std::cout << "Good's name: ";
		std::cin >> name;
		std::cout << "Price: ";
		std::cin >> price;
	}
	void display()
	{
		std::cout << "\n" << name;
		std::cout << ", Final price with tax: ";
		std::cout << static_cast<long>(price * (1.0 + goods::percent * 0.01));
		std::cout << "\n";
	}
};

int goods::percent = 20;

int main()
{
	std::array<goods, 3> a;
	for (auto&& i : a)
	{
		i.input();
	}
	for (auto&& i : a)
	{
		i.display();
	}
}

추상 메서드 편집

추상 메서드는 구현 없이 선언만 되어 있는 메서드를 말한다. 서브 클래스는 반드시 메서드의 구현을 포함하여야 한다. 추상 메서드는 언어에서 인터페이스를 명시하기 위해 사용된다.

예제 편집

아래의 자바 코드는 확장이 필요한 추상 클래스를 정의한 것이다.

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

위의 "Main" 클래스를 상속하는 클래스이다.

public class Main2 extends Main{

	@Override
	int rectangle(int h, int w)
	{
		return h*w;
	}

}

상태변이 메서드 편집

상태변이 메서드는 자신을 호출한 객체의 상태를 변화시킬 수 있는 메서드를 말한다.

예제 편집

struct calculator
{
	static int value;
	void increase()
	{
		value = value + 1;
	}
};

접근 메서드 편집

접근 메서드는 보통 단순히 객체의 상태에 접근할 수 있는 메서드를 말한다.

예제 편집

struct calculator
{
	static int value;
	void printValue()
	{
		printf("%d\n", value);
	}
};

정적 메서드 편집

정적 메서드는 클래스의 인스턴스 없이 데이터에 접근할 수 있는 권한을 가진다. 어떤 언어에서는 static 키워드를 선언부에 적음으로써 다른 것들과 구분 짓는다.

각주 편집

  1. Mark Slagell (2008). “Methods”. http://www.rubyist.net/~slagell/ruby/: Ruby User's Guide. 2011년 8월 27일에 원본 문서에서 보존된 문서. 2011년 8월 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. 2011년 10월 2일에 원본 문서에서 보존된 문서. 2011년 8월 12일에 확인함. Binding denotes association of a name with a class. 

같이 보기 편집