본문 바로가기
Java 배우기

Passing Information to a Method or a Constructor 메소드 또는 생성자에게 정보 전달하기

by 노화방지 Anti-aging Hairstyle 2016. 1. 5.
반응형

메소드 또는 생성자에게 정보 전달하기
  
Passing Information to a Method or a Constructor


메소드 또는 생성자 선언은  해당 메소드 또는 생성자의 아규먼트의 갯수와 타입을 선언합니다.
예를 들어, 아래는 대출금액, 이자율, 대출기간(기간 수) 및 미래 대출금액에 근거한, 가계대출
에 대한 매월 지급을 계산하는 메소드 입니다:

The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:

public double computePayment(
                  double loanAmt,
                  double rate,
                  double futureValue,
                  int numPeriods) {
    double interest = rate / 100.0;
    double partial1 = Math.pow((1 + interest), 
                    - numPeriods);
    double denominator = (1 - partial1) / interest;
    double answer = (-loanAmt / denominator)
                    - ((futureValue * partial1) / denominator);
    return answer;
}


이 메소드는 4개의 패러미터를 갖고 있습니다: 대출금액, 이자율, 미래 가치, 기간 수.
앞의 패러미터 3개는 double-precision floating point numbers이고, 네 번째 패러미터는 정수입니다.
패러미터들은 메소드 몸체에서 사용되는데, 런타임 시에 전달받은 아규먼트들의 값을 취합니다.

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.


참조: 패러미터들 메소드 선언 안의 변수들의 목록을 가리킵니다. 
아규먼트들 메소드가 invoke 되었을 때 전달되는 실제 값들입니다.
메소드를 invoke하면, 사용되는 아규먼트들은 선언에 있는 패러미터의 타입 및 순서와 일치해야 합니다.
Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.


패러미터 타입 Parameter Types


어떤 데이터 타입도 메소드 및 생성자의 패러미터로 사용할 수 있습니다.

여기에는, computePayment 메소드에서 본 것과 같은 doubles, floats integers와 같은 원시 데이터타입, 그리고 객체 및 배열과 같은 참조 데이터 타입이 포함됩니다.

배열을 아규먼트로 수용하는 메소드의 예제가 아래에 있습니다.
이 예에서, 메소드는 new Polygon 객체를 생성한 다음, Point 객체의 배열로부터  그것을 초기화 합니다 (Point는 x, y coordinate를 표현하는 클래스라고 가정):

You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.

Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):

public Polygon polygonFrom(Point[] corners) {
    // method body goes here
}

Note: If you want to pass a method into a method, then use a lambda expression or a method reference.


임의의 아규먼트 갯수  Arbitrary Number of Arguments


임의의 갯수의 값을 메소드에게 전달하기 위하여 varargs라는 construct를 사용할 수 있습니다.
메소드로 전달될 아규먼트의 특정 타입의 아규먼트의 갯수를 모를 때 varargs를 사용할 수 있습니다.
이는 배열을 수작업으로 생성하기 위한 지름길(shortcut) 입니다(앞의 메소드는 배열 대신 varargs를 사용했을 수도 있음).

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).


varargs를 사용하려면, ellipsis (3개의 점, ...), space, 패러미터 이름에 의한 마지막 패러미터 타입을 따라야 합니다.
그러면 아무 것도 포함되지 않은 어떤 갯수의 해당 패러미터로도 메소드를 call 할 수 있습니다. 

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point... corners) { int numberOfSides = corners.length; double squareOfSide1, lengthOfSide1; squareOfSide1 = (corners[1].x - corners[0].x) * (corners[1].x - corners[0].x) + (corners[1].y - corners[0].y) * (corners[1].y - corners[0].y); lengthOfSide1 = Math.sqrt(squareOfSide1); // 보다 많은 메소드 몸체 코드가 Points를 연결하는 polygon을 생성시켜서 리턴하는 것을 따름 }


메소드 안에서 corners는 배열 처럼 처리되는 것을 볼 수 있습니다.
메소드는 배열로 또는 일련의 아규먼트로 call 될 수 있습니다.
메소드 몸체 내의 코드는 패러미터를 다른 케이스 안에서의 배열로 처리할 것입니다.
You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.


프린팅 메소드를 가진 varargs를 아주 흔하게 볼 것입니다; 예를 들면, 이 printf 메소드: 

You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object... args)

임의의 갯수의 객체들을 프린트 할 수 있게 합니다. 아래 처럼 call될 수 있습니다:
allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);

or like this

System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email);

or with yet a different number of arguments.


패러미터 이름 Parameter Names


메소드 또는 생성자에 패러미터를 선언할 때, 해당 패러미터의 이름을 제공합니다.
이 이름은, 메소드 몸체 안에서, 전달되어 들어온 아규먼트를 참조하는데 사용됩니다.

패러미터의 이름은 그 범위 안에서 유일해야 합니다.
패러미터의 이름은 동일한 메소드 또는 생성자에서 다른 패러미터의 이름과 같을 수 없으며, 메소드 또는 생성자 내의 로컬 변수의 이름이 될 수 없습니다.

패러미터는 클래스의 필드 중 하나와 같은 이름을 가질 수 있습니다.
이 경우, 패러미터가 필드를 뒤따른다고(shadow) 말합니다.
필드를 뒤따르는 것은 코드를 읽기 어렵게 만들 수 있고, 협약 상, 특정 필드를 설정하는 생성자와 메소드 안에서만 사용됩니다.
예를 들어, 아래의 Circle 클래스 및 setOrigin 메소드를 검토해봅니다.

When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.

The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.

A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin method:

public class Circle {
    private int x, y, radius;
    public void setOrigin(int x, int y) {
        ...
    }
}


Circle 클래스는 3개의 필드 x, y, radius를 갖고 있습니다.
메소드 setOrigin은  2개의 패러미터를 갖고 있는데, 이들 각각은
필드 중 하나와 같은 이름을 갖고 있습니다.

각각의 메서드 패러미터는 그 이름을 공유하는 필드를 뒤따릅니다.
그래서 메소드의 몸체 안에서 간단한 이름 x 또는 y를 사용하는 것은 패러미터를 참조하는 것이지 필드를 참조하지 않습니다.
필드에 접근하려면 규정된 이름을 사용해야 합니다.
이것은 이 단원의 뒷부분에 있는 "this 키워드 사용" 섹션에서 논의됩니다.

The Circle class has three fields: xy, and radius. The setOrigin method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword."


Passing Primitive Data Type Arguments


int 또는 double과 같은 원시 아규먼트는 값(value)로 메소드에게 전달됩니다.
이것은 패러미터의 값에 대한 어떤 변경도 메소드의 범위 안에서만 존재한다는 것을 의미합니다.
메소드가 리턴하면, 패러미터는 없어지고 그 패러미터에 대한 어떤 변경도 잃어버립니다.
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. 


여기 그 예가 있습니다: Here is an example:

public class PassPrimitiveByValue {

    public static void main(String[] args) {
           
        int x = 3;
           
        // invoke passMethod() with 
        // x as argument
        passMethod(x);
           
        // print x to see if its 
        // value has changed
        System.out.println("After invoking passMethod, x = " + x);
           
    }
        
    // change parameter in passMethod()
    public static void passMethod(int p) {
        p = 10;
    }
}


이 프로그램을 가동하면 산출물은:

When you run this program, the output is:

After invoking passMethod, x = 3


참조 데이터타입 아규먼트 전달하기 
Passing Reference Data Type Arguments

객체와 같은 참조 데이터타입 패러미터들도 또한 value로 메소드에게 전달됩니다.
이는, 메소드가 반환되면, 전달된 참조는 여전히 이전과 동일한 객체를 참조함을 의미합니다.
하지만 그들이 적절한 접근 레벨을 갖고 있다면, 객체 필드의 값은 메소드 안에서 변경될 수 있습니다.
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

예를 들어, Circle 객체를 움직이는 임의의 클래스 안에 있는 메소드를 고려해봅니다:

For example, consider a method in an arbitrary class that moves Circle objects:

public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);
        
    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}

Let the method be invoked with these arguments:

moveCircle(myCircle, 23, 56)

Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (i.e., myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Thencircle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to bycircle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.



반응형

댓글