
접근제한자 반환타입 메서드이름() // 선언부
{
기능을 수행할 코드 // 실행 영역
}
// 접근 제한자 : 해당 메서드에 접근할 수 있는 범위 결정
// 반환 타입 : 어떤타입으로 반환할 것인지 타입을 미리 정해줌.
// 반환값이 없는 경우에는 반환 타입으로 void 사용
// 메서드 이름 : 이름을 가지고, 메서드를 호출할 때 사용
메서드가 있는 클래스 참조변수 = new 클래스();
참조변수.메서드 이름();
// 단, 같은 클래스에 있는 메서드를 호출할 떄에는 메서드 이름만 호출
Book b = new Book();
b.read();
public class Sample {
int sum(int a, int b) { // a, b 는 매개변수
return a+b;
}
public static void main(String[] args) {
Sample sample = new Sample();
int c = sample.sum(3, 4); // 3, 4는 인수
System.out.println(c);
}
}
접근제한자 반환타입 메서드 이름(자료형 변수명 ...) {
// 기능을 수행할 코드들
}
int number;
// int : 호출할 때 전달받을 변수의 자료형
// number : 전달받을 매개변수를 메서드 안에서 사용할 때 이름
분류
int sum(int a, int b) // 입력값 {
return a+b; // 리턴값
}
// sum메서드는 두 개의 입력값을 받아서 서로 더한 결괏값을 돌려주는 메서드
// 메서드 사용 방법
Sample sample = new Sample();
int result = sample.sum(3, 4);
void say() // 입력값 없음, 리턴값 void {
System.out.println("Hi");
}
// 메서드 사용 방법
public class Sample {
void say() {
System.out.println("Hi");
}
public static void main(String[] args) {
Sample sample = new Sample();
sample.say(); // Hi
}
}
String say() // 입력값 없음, 리턴값 String {
return "Hi";
}
// 메서드 사용 방법
public class Sample {
String say() {
return "Hi";
}
public static void main(String[] args) {
Sample sample = new Sample();
String a = sample.say();
System.out.println(a); // "Hi" 출력
}
}
void sum(int a, int b) // 입력값 int a int b, 리턴값 void {
System.out.println(a+"과 "+b+"의 합은 "+(a+b)+"입니다.");
}
// 메서드 사용 방법
public class Sample {
void sum(int a, int b) {
System.out.println(a+"과 "+b+"의 합은 "+(a+b)+"입니다.");
}
public static void main(String[] args) {
Sample sample = new Sample();
sample.sum(3, 4);
}
}