제어자
반환타입
메소드명
(타입 변수1, 타입 변수2...)
{}
제어자
: (default) / static ...
반환타입
: int / long / double / void ...
타입 매개변수명
은 0~n개 가능
: 메소드 내에 선언된 변수
메소드가 종료되면 사라짐
-> 메소드1, 2의 (지역)변수의 이름이 같아도 상관없다.
매개변수도 지역변수임!!
int add(int x, int y)
{
int result = x + y;
return result;
}
-> 여기서 지역변수lv는 x, y, result !
class MyMath {
//...
long add(long x, long y) {
//...
}
double divide(long x, long y) {
//...
}
static void method() {
//...
}
//...
}
static
제어자가 없는 메소드①✨✨ 객체 생성 후
MyMath mm = new MyMath();
②✨✨ 참조변수.메소드명(); 으로 호출한다!!
long result1 = mm.add(5L, 3L);
long result2 = mm.substract(5L, 3L);
long result3 = mm.multiply(5L, 3L);
double result4 = mm.divide(5L, 3L);
long result5 = mm.max(5L, 3L);
static
제어자가 있는 메소드① 객체 생성이 💖필요 없다💖
②🎇🎇 메소드명(); 으로 호출한다!!
②🧨🧨 클래스명.메소드명(); 으로 호출한다!!
method();
int Result = add(3, 5);
MyMath2.method();
static int add(int x, int y) {
return x+y;
}
public static void main (String [] args) {
...
...
print99danall();
int Result = add(3, 5);
...
}
👀👀 print99danall();
은 메소드 호출에 왜 옆에 변수가 없나?
-> ✨ 아무것도 반환하지 않는 void
형이기 때문에
-> void print99danall();
👀👀 add();
는 메소드 호출에 왜 옆에 변수가 필요하나?
-> ✨ 작업결과가 있기에, 이 작업결과인 반환값int
을 저장할 변수가 필요하다.
-> 없다고 에러가 나진 않으나, 저 메소드를 호출한 결과를 사용할 수가 없다.
자바의정석 Ex6_4
public class Ex6_4 {
public static void main(String[] args) {
// 메서드 호출 관련 예제
MyMath mm = new MyMath(); // 객체 생성=인스턴스 생성
long result1 = mm.add(5L, 3L);
// 호출한 메소드의 결과값을 메인안에 있는 변수에 저장
// static이 아닌 메소드이므로, 객체생성 및 리모컨인 mm.이 필요하다.
long result2 = mm.subtract(5L, 3L);
long result3 = mm.multiply(5L, 3L);
double result4 = mm.divide(5L, 3L);
long result5 = mm.max(5L, 3L);
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);
System.out.println("max(5L, 3L) = "+result5);
}
}
//MyMath 라는 클래스 설계도
class MyMath {
long add(long a, long b) {
long result = a + b;
return result;
// return a + b; 라고 한 줄로 정리할 수 있다!
}
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;
}
long max(long a, long b) {
return (a>b)? a : b;
}
}
add(5L, 3L) = 8
subtract(5L, 3L) = 2
multiply(5L, 3L) = 15
divide(5L, 3L) = 1.6666666666666667
max(5L, 3L) = 5
: 함수뿐만 아니라 관련된 변수까지도 한꺼번에 묶어서 관리하고 재사용할 수 있게 해주는 것
: 클래스에 포함된 변수
: 클래스에 포함된 함수
return 생략 가능
메소드 안의 system.out.print();
등은 가능하다. 이건 반환이 아니니까!
👀 return
이 있다면??
-> ✨메서드 종료✨하고 호출한 곳으로 돌아가라!!