개발지식

JAVA 기초 지식 8 (method, 오버로드)

mat_hoyoung 2022. 6. 28.
public class Main {
    public static void main(String[] args) {
        add(50, 10);  // 순서2 다른 메서드에서 호출에서 자유롭게 사용할 수 가 있음.
        add(100, 150);
    }

    public static void add(int x, int y) {     // 순서1  add 라는 이름의 메서드 parameter로 x와 y를 더함
        System.out.println(x+y);
    }
}

 

public class Main {
    public static void main(String[] args) {
        System.out.println(add(50, 10)); // 다른 메서드에서 호출에서 자유롭게 사용할 수 가 있음.
        System.out.println(add(100, 150));
    }

    public static int add(int x, int y) {// add 라는 이름의 메서드 parameter로 x와 y를 더함
        return x + y;
    }
}

return 값을 이용하여 메인 method 에서 출력 할 수 있도록 한 것. 

 

public static int add(int ... numbers) {/// ...은 0개부터 숫자를 제한하지 않는 값을 넣어도되고 안넣어도되는 들어오게되면 배열로 들어옴(for문을 통해서 하나씩 꺼내올 수 있음)
    int sum = 0;
    for(int i = 0; i < numbers.length; i++){
        sum = sum + i;
    }
    return sum;
}
System.out.println(add(1 ,2 ,3 ,4 ,5));

결과 값은 10이 나옴. 

댓글