반응형

메소드

 

- 메소드는 클래스가 수행할 수 있는 기능 정의

 

메소드 형태

 

리턴할 타입 메소드명 (파라미터1....) {

   내용;

}

 

- 메소드에 인자를 전달할 경우 값이 그대로 전달된다. 예시를 보여드리겠습니다.

 

int hap(int num1, int num2) {

      return num1 + num2;

}

위와 같은 메소드를 정의하고 다음과 같이 호출 할 수 있습니다.

int result = hap(100,200)

 

간단한 예를 들어보겠습니다.

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

class CarSpeed { 

 

    int speed; 

    public String irum; 

    

    //메소드 정의

    void speedhap(CarSpeed myCar) {

        

        myCar.speed += 50;

        

    }

}

 

public class MyCar { 

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        

        CarSpeed myCar = new CarSpeed();

        

        //변수 사용

        myCar.speed = 60;

        myCar.irum = "홍길동";

        

        //메소드사용

        

        

        myCar.speedhap(myCar);

        System.out.println(myCar.speed);

    }

 

}

 

 

1줄 - 변수 speed와 irum을 정의해주었습니다.

28줄 - speedhap 메소드를 실행하면 객체변수 speed의 값이 변경됩니다.

따라서 출력 결과는 다음과 같습니다.

 

 

출력 결과

 

1

110

 

메소드 오버로딩

 

- 같은 이름의 메소드를 한 클래스에 여러 개 정의할 수 있다.

 

메소드 오버로딩의 규칙

 

1) 파라미터의 타입이나 개수가 달라야 한다.

 

void 메소드명(int price);

void 메소드명(String name);

 

void 메소드명(int price, String name);

 

2) 파라미터의 이름은 오버로딩 성립에 영향을 주지 않는다.

 

void 메소드명(int x);

void 메소드명(int y);

 

3) 리턴 타입은 오버로딩 성립에 영향을 주지 않는다.

 

void 메소드명(int x);

int 메소드명(int x);

 

예문을 보도록 하겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
class ProDuctions {
 
    String name;
    int price;
 
 
    public void display() {
        name = "감자";
        price = 456789;
 
        System.out.println("상품명 : " + name + " // 가격 : " + price );
    }
 
    public void display(String name) {
 
        System.out.println("상품명 : " + name + " // 가격 : " + price);
    }
 
    public void display(String name, int price) {
 
        System.out.println("상품명 : " + name + " // 가격 : " + price);
    }
 
}
 
public class ProductionMain {
 
    public static void main(String[] args) {
        ProDuctions pd = new ProDuctions();
 
        pd.display();
 
        pd.display("고구마");
 
        pd.display("왕감자"50000);
 
    }
 
}
 
 

9 - 13번, 33째 줄 - 선언한 변수에 변수 데이터값을 "감자"와 456789로 지정 해주었으므로 감자와 456789를 출력 할 것이다. 

16 - 18, 35번째 줄 - 메소드 오버로딩을 통해 파라미터 name을 새롭게 정의하여 "고구마"와 456789를 출력한다.

21 - 23, 37번째 줄 - 메소드 오버로딩을 통해 name과 price를 다시 정의하여 "왕감자"와 50000을 출력한다.

 

출력결과

1
2
3
상품명 : 감자 // 가격 : 456789
상품명 : 고구마 // 가격 : 456789
상품명 : 왕감자 // 가격 : 50000

 

반응형

'JAVA > JAVA' 카테고리의 다른 글

9 - 상속  (0) 2020.03.04
8 - 생성자(Constructor)  (0) 2020.03.04
6 - 클래스 ( class )  (0) 2020.03.03
5 - 배열(Arrary)  (0) 2020.03.03
4 - 조건문 if & switch  (0) 2020.03.03

+ Recent posts