JAVA chapter 06. 클래스. 


6.8 메소드

6.8.1 메소드 선언



// 매개값의 타입(byte)과 매개 변수의 타입(int)이 달라도 byte 타입은 int타입으로 자동 타입 변환되기 때문에 컴파일 오류가 생기지 않는다



Calculator.java // 메소드 선언

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Calculator {
    //메소드
    void powerOn() {
        System.out.println("전원을 켭니다.");
    }
    
    int plus(int x, int y) {
        int result = x + y;
        return result;
    }
    
    double divide(int x, int y) {
        double result = (double)x / (double)y;
        return result;
    }
    
    void powerOff() {
        System.out.println("전원을 끕니다");
    }
}
cs

CalculatorExample.java // 메소드 호출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CalculatorExample {
    public static void main(String[] args) {
        // 외부 클래스 Calculator 클래스의 메소드를 호출하기 위해서는 Calculator 객체를 생성하고 참조 변수인 myCalc를 이용해야 한다.
        Calculator myCalc = new Calculator();
myCalc.powerOn();
        
        int result1 = myCalc.plus(56);
        System.out.println("result1: " + result1);
        
        byte x = 10;
        byte y = 4;
        double result2 = myCalc.divide(x, y); // byte타입은 int타입으로 자동 타입 변환 되기 때문에 컴파일 오류가 생기지 않는다
        System.out.println("result2: " + result2);
        
        myCalc.powerOff();
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Computer {
    int sum1(int[] values) { // 1. 매개변수를 배열로 선언
        int sum = 0;
        for(int i=0; i<values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
    
    int sum2(int ... values) { // 2. 매개변수를 ... 로 선언 (자동으로 배열 생성)
        int sum = 0;
        for(int i=0; i<values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ComputerExample {
    public static void main(String[] args) {
        Computer myCom = new Computer();
        
        int[] values1 = {123};
        int result1 = myCom.sum1(values1);
        System.out.println("result1: " + result1);
        
        int result2 = myCom.sum1(new int[] {12345});
        System.out.println("result2: " + result2);        
        
        int result3 = myCom.sum2(123);
        System.out.println("result3: " + result3);
        
        int result4 = myCom.sum2(12345);
        System.out.println("result4: " + result4);
    }
}
 
cs




6.8.2 리턴(return)문


// 리턴문의 리턴값은 리턴 타입이거나 리턴 타입으로 변환될 수 있어야 한다.

// 예를 들어 리턴 타입이 int인 plus() 메소드에서 byte, short, int 타입의 값이 리턴되어도 상관없다.

// byte와 short은 int로 자동 타입 변환되어 리턴되기 때문이다.


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
package sec08.exam02_return;
 
public class Car {
    //필드
    int gas;
    
    //생성자
    
    //메소드
    void setGas(int gas) {
        this.gas = gas;
    }
    
    boolean isLeftGas() {
        if(gas==0) {
            System.out.println("gas가 없습니다."); 
            return false;
        }
        System.out.println("gas가 있습니다."); 
        return true;
    }
    
    
    void run() {
        while(true) {
            if(gas > 0) {
                System.out.println("달립니다.(gas잔량:" + gas + ")");
                gas -= 1;
            } else {
                System.out.println("멈춥니다.(gas잔량:" + gas + ")");
                return;
            }
        }
    }
}
 
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package sec08.exam02_return;
 
public class CarExample {
    public static void main(String[] args) {
        Car myCar = new Car();
        
        myCar.setGas(5);  //Car의 setGas() 메소드 호출
        
        boolean gasState = myCar.isLeftGas();  //Car의 isLeftGas() 메소드 호출
        if(gasState) {
            System.out.println("출발합니다.");
            myCar.run();  //Car의 run() 메소드 호출
        }
        
        if(myCar.isLeftGas()) {  //Car의 isLeftGas() 메소드 호출
            System.out.println("gas를 주입할 필요가 없습니다.");
        } else {
            System.out.println("gas를 주입하세요.");
        }
    }
}
 
 
cs




6.8.3 메소드 호출




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Calculator {
    //필드
    //생성자
    //메소드
    int plus(int x, int y) {
        int result = x + y;
        return result;
    }
    
    double avg(int x, int y) {
        double sum = plus(x, y);
        double result = sum / 2; // result = 8.5(int 타입은 double 타입으로 자동형변환)
        return result;
    }
    
    void execute() {
        double result = avg(710);
        println("실행결과: " + result);
    }
    
    void println(String message) {
        System.out.println(message);
    }    
}
cs

1
2
3
4
5
6
public class CalculatorExample {
    public static void main(String[] args) {
        Calculator myCalc = new Calculator(); // 객체 생성
        myCalc.execute();
    }
}
cs




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Car {
    //필드
    int speed;
    
    //생성자
    
    //메소드
    int getSpeed() {
        return speed;
    }
    
    void keyTurnOn() {
        System.out.println("키를 돌립니다.");
    }    
    
    void run() {
        for(int i=10; i<=50; i+=10) {
            speed = i;
            System.out.println("달립니다.(시속:" + speed + "km/h)");
        }
    }    
}
 
cs

1
2
3
4
5
6
7
8
9
10
public class CarExample {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.keyTurnOn();
        myCar.run();
        int speed = myCar.getSpeed();
        System.out.println("현재 속도: " + speed + "km/h");
    }
}
 
cs



6.8.4 메소드 오버로딩(Overloading)

// 매개 변수의 타입과 개수, 순서가 똑같을 경우 매개 변수 이름만 바꾸는 것은 메소드 오버로딩이라고 볼 수 없다.

// 또한 리턴 타입만 다르고 매개 변수가 동일하다면 이것은 오버로딩이 아니다.

1
2
3
4
5
6
7
8
9
10
11
public class Calculator {
    //정사각형의 넓이
    double areaRectangle(double width) {
        return width * width;
    }
    
    //직사각형의 넓이
    double areaRectangle(double width, double height) { // int는 double로 자동 형변환
        return width * height;
    }    
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CalculatorExample {
    public static void main(String[] args) {
        Calculator myCalcu = new Calculator();
        
        //정사각형의 넓이 구하기
        double result1 = myCalcu.areaRectangle(10);
 
        //직사각형의 넓이 구하기
        double result2 = myCalcu.areaRectangle(1020);
        
        //결과 출력
        System.out.println("정사각형 넓이=" + result1);
        System.out.println("직사각형 넓이=" + result2);
    }
}
cs






Posted by 너래쟁이
: