1. 동일한 작얼의 코드들을 묶어 놓은 것
메서드의 장점
- 코드의 중복을 줄일 수 있다.
- 코드의 관리가 쉽다.
-코드를 재사용할 수 있다
-코드가 간결해서 이해하기 쉬워진다
매서드 = 선언부 + 구현부
반환타입 메서드이름 (타입변수명,타입 변수명, ...) - 선언부
{ 메서드 호출시 수행될 코드 } - 구현부
지역변수 : 메서드 내에 선언된 변수
지역변수 내에 매개변수 이름은 겹쳐
package javachap06;
public class Ex_64 {
public static void main(String[] args) {
// 2. MyMath 객체생성
MyMath mm = new MyMath();
// 3. MyMath 객체사용 ( 객체의 메서드 호출 )
long result1 = mm.add(5L, 3L); // add메서드 호출
long result2 = mm.subtract(5L, 3L);
long result3 = mm.multiply(5L, 3L);
long result4 = (long)mm.divide(5, 3);
System.out.println("add(5L, 3L) = " + result1);
System.out.println("subtract(5L, 3L) = " + result2);
System.out.println("multiply(5L, 3L) = " + result3);
System.out.println("divide(5L, 3L) = " + result4);
}
}
// 1 MyMath클래스 작성 ( 메서드 작성 )
class MyMath{
long add(long a, long b) {
long result = a + b;
return result; // 작업을 마치면 호출한곳으로 돌아간다
}
long subtract(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;
}
}
---------------------------------------------------------------------------
add(5L, 3L) = 8
subtract(5L, 3L) = 2
multiply(5L, 3L) = 15
divide(5L, 3L) = 1
'JAVA' 카테고리의 다른 글
객체지향 static 메서드와 instance 메서드 (0) | 2022.09.25 |
---|---|
객체지향 호출 스택(call stack) (0) | 2022.09.24 |
객체지향 선언 위치에 따른 변수의 종류 (0) | 2022.09.24 |
객체지향 객체 배열 (0) | 2022.09.24 |
객체지향 객체의 생성과 사용 (0) | 2022.09.24 |