메소드 정의하기 Defining Methods
아래는 전형적 메소드 선언의 예 입니다: Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
메소드 선언의 필수항목은 메소드의 return 타입, 이름, 한 쌍의 괄호 ()
, 그리고 중괄호 {}
사이의 몸체 입니다.
보다 일반적으로, 메소드 선언들은 다음의 6개 구성요소를 순서대로 갖고 있습니다:
The only required elements of a method declaration are the method's return type, name, a pair of parentheses, ()
, and a body between braces, {}
.
More generally, method declarations have six components, in order:
- 제한자— 나중에 배우게 될
public
,private
등.
Modifiers—such aspublic
,private
, and others you will learn about later. - 리턴 타입— 메소드가 리턴하는 값의 데이터타입, 또는 메소드가 값을 반환하지 않는 경우의
void
.
The return type—the data type of the value returned by the method, orvoid
if the method does not return a value. - 메소드 이름- 필드 이름에 대한 규칙이 메소드 이름에 적용되지만 협약은 약간 다릅니다.
The method name—the rules for field names apply to method names as well, but the convention is a little different. - 괄호 안의 패러미터- 콤마로 분리된 투입 패러미터들의 목록, 그 앞에는 데이터 타입이고, 괄호()로 닫힙니다.
패러미터가 없으면 빈 괄호를 사용해야 합니다.
The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses,()
. If there are no parameters, you must use empty parentheses. - 예외 목록- 나중에 논의. An exception list—to be discussed later.
- 중괄호 사이의 메소드 몸체- 로컬 변수 선언을 포함한 메소드의 코드
The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.
Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
메소드 이름 짓기 Naming a Method
메소드 이름이 어떤 legal identifier이어도 되지만, 코드 협약은 메소드 이름을 제한하고 있습니다.
협약에 따르면, method 이름은 소문자의 동사이거나 또는 소문자의 동사로 시작되고, 형용사, 명사 등이 뒤따르는 복합단어(multi-word) 이름이어야 합니다.
복합단어 이름에서, 두 번째 및 이어지는 단어들의 각각의 첫 째 글자는 대문자 이어야 합니다.
여기 몇 가지 예가 있습니다:
Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:
run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty
전형적으로, 메소드는 클래스 안에서 유일한 이름을 갖고 있습니다. 하지만 메소드는 메소드 오버로딩 때문에 다른 메소드와 동일한 이름을 가질 수도 있습니다.
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.
메소드 오버로딩 Overloading Methods
자바 프로그래밍 언어는 overloading 메소드들을 지원하며, 자바는 서로 다른 메소드 signatures로 메소드들을 구분할 수 있습니다.
이 말은 클래스 내의 메소드들이 각기 다른 패러미터 목록을 갖고 있다면 동일한 메소드 이름을 가질 수 있음을 의미합니다(이에 대한 몇 가지 qualifications은 "Interfaces 및 Inheritance" 라는 제목의 단원에서 논의될 것임).
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").
다양한 타입의 데이터(strings, integers 등)를 그릴 수 있는 calligraphy를 사용할 수 있고, 각 데이터 타입을 그리기 위한 메소드를 포함하고 있는, 클래스를 갖고 있다고 가정합니다.
예를 들어 drawString
, drawInteger
, drawFloat
등 처럼 각 메소드 별로 새로운 이름을 갖는 것은 매우 귀찮은 일입니다 - .
자바 프로그래밍 언어에서, 모든 drawing 메소드들이 같은 이름을 가질 수 있지만 각 메소드 별로 다른 argument 목록을 전달합니다.
이와 같이, data drawing 클래스는 각자 서로 다른 패러미터 목록을 가진, draw
란 이름의 4개의 메소드를 선언할 수 있습니다.
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example,drawString
, drawInteger
, drawFloat
, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw
, each of which has a different parameter list.
public class DataArtist {
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
오버로드 메소드들은 메소드로 전달되는 아규먼트의 갯수와 타입으로 구분합니다.
코드 샘플에서, draw(String s)
와 draw(int i)
는 구분되며 각자 유일한 메소드들인데, 그 이유는 각자 다른 아규먼트 타입을 요구하기 때문입니다.
같은 이름, 같은 아규먼트 갯수와 타입으로 메소드를 2개 이상 선언하면 컴파일러가 구분할 수 없습니다.
메소드를 구분할 때 리턴 타입은 고려하지 않기 때문에, 리턴 타입이 다른 것을 갖고 있더라도 같은 시그니처를 가진 메소드를 2개 선언할 수 없습니다.
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s)
and draw(int i)
are distinct and unique methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
주: 오버로드된 메소드들은 가능한 삼가해야 하는데, 그 이유는 오버로드되면 가독성이 떨어지기 때문입니다.
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
'Java 배우기' 카테고리의 다른 글
Passing Information to a Method or a Constructor 메소드 또는 생성자에게 정보 전달하기 (0) | 2016.01.05 |
---|---|
Providing Constructors for Your Classes 클래스에 생성자 제공하기 (0) | 2016.01.05 |
Declaring Member Variables 멤버변수 선언하기 (0) | 2016.01.05 |
Declaring Classes 클래스 선언하기 (0) | 2016.01.05 |
Classes 클래스 (0) | 2016.01.05 |
댓글