Programming Language/JAVA

메서드 호출

Glory-L 2023. 2. 16. 16:54

메서드의 호출

 

* 메서드를 호출하는 방법

 : 메서드 이름 ( 값1, 값2 , ....) ;      

 

 

print99danAll();	// void print99danAll()을 호출
int result = add(3, 5);	// int add(int x, int y)를 호출하고, 결과를 result에 저장

 

 


 

 

메서드의 호출 예시

 

 

class MethodEx {

	public static void main(String args[]) {
    
    	MyMath mm = new MyMath(); // 계산식이 있는 클래스인 MyMath 객체 생성
        
        long result = mm.max(5, 3);	// MyMath의 math 메서드 호출
        long result1 = mm.add(5, 3);	// MyMath의 add 메서드 호출
        long result2 = mm.subtract(5L, 3L);	// MyMath의 subtract 메서드 호출
        long result3 = mm.multiply(5L, 3L); // MyMath의 multiply 메서드 호출
        double result4 = mm.divide(5L, 3L); // MyMath의 divide 메서드 호출
    	
        System.out.println(" max(5L, 3L) = " + result);
        System.out.println(" add(5L, 3L) = " + result1);
        System.out.println(" substract(5L, 3L) = " + result2);
        System.out.println(" multiply(5L, 3L) = " + result3);
        System.out.println(" divide(5L, 3L) = " + result4);
    }

}

class MyMath {

	long add(long a, long b) {
    	long result = a + b;
        return result;
    // return a + b;	// 위의 두줄 코드를 return 하나로 간단히 할 수 있다. 
    }
    
    long substract(long a, long b) { return a - b; }
    long multiply(long a, long b) {return a * b; }
    double divide(double a, double b) {
    	return a / b;
    }

}

 

 

 


 

 

메서드 실행 흐름 

 

 

 

 

[ 자바의 정석 - 기초 유튜브 강의 영상 참고 ]

https://www.youtube.com/watch?v=6_GxMvWbkXw&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp&index=60