728x90
함수 (Function)
독립적인 코드 블럭으로 특정 작업 수행
객체 (클래스)에 속하지 않고, 전역적 또는 모듈 단위로 존재
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
메서드 (Method)
클래스 또는 객체에 속하는 함수
- 특정 객체에 대한 동작을 정의
- 객체를 통해 호출됨
const person = {
name: "Alice",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet());
함수와 메서드의 차이
구분 | 함수 (Function) | 메서드 (Method) |
소속 | 클래스와 무관 (독립적) | 클래스 또는 객체 내부에 존재 |
호출 방식 | 직접 호출 | 객체를 통해 호출 |
예제 | `add(3, 5)` | `calc.add(3, 5)` |
모든 메서드는 함수이지만, 모든 함수가 메서드는 아님
In Java
Java에선 클래스 바깥에 함수를 정의할 수 없기 때문에 모든 함수는 메서드로 존재 해야 함.
하지만, `static 메서드`와 `인스턴스 메서드`로 함수와 메서드의 차이를 알 수 있음
static 메서드
class MathUtil {
// static 메서드는 특정 객체 없이 호출 가능 → 일반적인 함수처럼 동작
public static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtil.add(3, 5); // 객체 없이 호출
System.out.println(result); // 8
}
}
`MathUtil.add()`는 static 메서드이므로 객체를 생성하지 않고 직접 호출 가능
객체를 통해 호출하는 메서드
class Calculator {
// 인스턴스 메서드 (객체를 통해 호출해야 함)
public int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // 객체 생성
int result = calc.multiply(3, 5); // 객체를 통해 호출
System.out.println(result); // 15
}
}
- `multiply()`는 객체가 있어야 호출 가능
- 함수보다는 객체 지향적 방식 (OOP)의 메서드
728x90