본문 바로가기

Etc../SWExpertAcademy

[Java Programming] 객체지향 핵심 원리(4)

메서드 Overloading과 매개변수

■ 메서드 Overloading

변수의 중복 선언

  • 변수는 데이터 타입이 달라도 이름이 동일한 경우를 허용하지 않음
  • 클래스 안에 동일한 이름의 변수를 사용했을 때, 프로그램이 모호해지기 때문.

메서드의 중복 정의

  • 변수와 달리 하나의 클래스에 동일한 이름의 메서드는 여러개 정의할 수 있음
  • 매개변수의 개수와 타입을 통해 실행될 메서드를 구분할 수 있기 때문
  • 이를 메서드 Overloading이라 함.
public class Employee{
    String name;
    int age;

    void setEmployee(String name, int age){
        this.name = name;
        this.age = age;
    }

    void setEmployee(String name){
        this.name = name;
    }

    void setEmployee(String name){
        name = "No Name";
        age = 0;
    }
}

매개변수의 인자나 데이터타입이 변경되더라도 메서드를 수정할 필요가 없어지게 됨.


메서드 Overloading의 유형

  • 매개변수의 개수와 타입이 모두 다른경우

  • 리턴타입이 다르고 매개변수가 같으면 Oberloading이 아님.(오류 발생)

  • 매개변수의 이름이 다른것 (오류발생)

  • 매개변수의 개수와 타입이 같지만 순서가 다른 경우 Overloading으로 인식

  • 매개변수가 형변환된 다른 타입인 경우

  • void calc(double d){
        System.out.println(d+d);
    }
    public static void main(String[] args){
        calc(45); //int는 double로 묵시적 형변환이 가능하여 실행 가능.
    }

코드가 중복되어 있는 경우
public class Employee{
    int employeeNo;
    String name;
    int age;
    int salary;

    public Employee(){
        this(0,"anonymity",0,0;)
    }
    public Employee(int employeeNo, String name){
        this.employeeNo = employeeNo;
        this.name = name;
    }
    public Employee(int employeeNo, String name, int age, int salary){
        this.employeeNo = employeeNo;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }    
}



■ 매개변수

매개변수의 의미

  • 메서드를 호출해서 객체 간 메세지를 전달할 때 매개변수로 전달됨
  • 메서드 매개변수로 전달되는 데이터가 기본형이냐 참조형이냐에 따라 동작 방식이 달라짐

기본형
int score = 80;
System.out.println(score);

int copyScore = score;
System.out.prinln(copyScore);
  • 변수 score을 수정해도 copyScore에는 영향을 미치지 않음.
  • copyScore을 수정해도 score에는 영향을 미치지 않음

참조형
int[] list = {100, 85, 99};
System.out.println(list[0]);

int[] copyList = list;
System.out.prinln(copyList[0]);
  • 배열 list의 특정 값을 수정하면 copyList에도 영향을 미침
  • 배열 copyList의 특정 값을 수정하면 list에도 영향을 미침
  • copyList는 list의 주솟값을 복사해 할당받기 때문


class Pair{
    int x,y;
    Pair(int x, int y){
        this.x = x;
        this.y = y;
    }
}
class swapTest{
    public static void swap(int x, int y){
        int tmp;

        tmp = x;
        x = y;
        y = tmp;
    }

    public static void swap(Pair p){
        int tmp;

        tmp = p.x;
        p.x = p.y;
        p.y = tmp;
    }
    public static void main(String[] args){
        int x = 10, y = 20;
        Pair p = new Pair(10,20);

        swap(x,y);                // 출력 시 변경되지 않음
        swap(p);                // p.x, p.y 출력 시 변경되어 있음
    }
}

가변적 매개변수(Variable Argument)

  • 매개변수 개수가 지정되어야만 하는 제한을 극복하기 위한 기능
  • 매개변수의 숫자를 컴파일이나 실행 시 미리 지정하지 않음
  • 하나의 메서드만 정의하여 매개벼수의 개수를 가변적으로 사용하는 방식
int intSum(int... num){
    int sum = 0;
    for(int i=0; i<num.length; i++)
        sum += num[i];
    return sum;
}

intSum(1);
intSum(1,2);
intSum(1,2,3,4,5,6);

가변적 매개변수의 규칙
  • 매개변수 선언 시 마지막으로 사용되어야 함 err) sum(int...i, String S)
  • 가변적 인자는 메서드에서 하나만 사용되어야 함
public class VariableArgumentTest{
    public static double scoreSum(double... score){
        double sum=0;
        for(int i=0; i<score.length; i++)
            sum += score[i];
        return sum;
    }

    public static void main(String args[]){            //인자의 개수는 유동적
        System.out.println(scoreSum(80,60));    //묵시적 형변환에 의해 실수형으로 반환되어 전달
        System.out.println(scoreSum(54.2,78.5,65.3));    
    }
}






[참고] : SWExpertAcademy