λ©μλλ νΉμ μμ μ μννλ μ½λ λΈλ‘μ λνλ΄λ©°, νμν λ νΈμΆνμ¬ μ¬μ©ν μ μμ΅λλ€.
λ©μλλ μ½λλ₯Ό λͺ¨λννκ³ μ¬μ¬μ©μ±μ λμ΄κΈ° μν μ€μν κ°λ μ€ νλμ λλ€.
μλ°μμλ μΈμ€ν΄μ€ λ©μλμ ν΄λμ€ λ©μλ(λλ μ μ λ©μλ) λ κ°μ§ μ νμ λ©μλκ° μμ΅λλ€. μ΄ λ μ νμ λ©μλλ μλ‘ λ€λ₯Έ μ©λμ νΈμΆ λ°©μμ κ°μ§κ³ μμ΅λλ€.
1. μΈμ€ν΄μ€ λ©μλ (Instance Method)
μΈμ€ν΄μ€ λ©μλλ νΉμ κ°μ²΄μ μΈμ€ν΄μ€μ μ’ μλ λ©μλμ λλ€. μ¦, κ°μ²΄λ₯Ό μμ±ν΄μΌλ§ ν΄λΉ λ©μλλ₯Ό νΈμΆν μ μμ΅λλ€. μΈμ€ν΄μ€ λ©μλλ λ€μκ³Ό κ°μ νΉμ§μ κ°μ§λλ€:
- λ©μλ μ μ μ static ν€μλκ° μμ΅λλ€.
- λ©μλ λ΄μμ μΈμ€ν΄μ€ λ³μμ μ κ·Όν μ μμ΅λλ€.
- κ°μ²΄λ₯Ό μμ±ν νμμΌλ§ ν΄λΉ λ©μλλ₯Ό νΈμΆν μ μμ΅λλ€.
public class MyClass {
private int value;
// μΈμ€ν΄μ€ λ©μλ
public void setValue(int newValue) {
value = newValue;
}
}
MyClass myObject = new MyClass(); // λ©μλ μ¬μ© μν΄ κ°μ²΄ μμ± νμ
myObject.setValue(10);
2. ν΄λμ€ λ©μλ (Static Method)
ν΄λμ€ λ©μλλ νΉμ μΈμ€ν΄μ€μ μνμ§ μκ³ , ν΄λμ€ μ체μ μν λ©μλμ λλ€. κ°μ²΄λ₯Ό μμ±νμ§ μκ³ λ ν΄λμ€μ μ΄λ¦μ ν΅ν΄ μ§μ νΈμΆν μ μμ΅λλ€. ν΄λμ€ λ©μλλ λ€μκ³Ό κ°μ νΉμ§μ κ°μ§λλ€:
- λ©μλ μ μ μ static ν€μλκ° μ¬μ©λ©λλ€.
- ν΄λμ€ λ³μμλ§ μ κ·Όν μ μμΌλ©°, μΈμ€ν΄μ€ λ³μμλ μ§μ μ κ·Όν μ μμ΅λλ€.
- κ°μ²΄λ₯Ό μμ±νμ§ μκ³ λ νΈμΆν μ μμ΅λλ€.
public class MathOperations {
// ν΄λμ€ λ©μλ
public static int add(int a, int b) {
return a + b;
}
}
int sumResult = MathOperations.add(5, 3); // κ°μ²΄ μμ± μμ΄ μ κ·Ό
System.out.println(sumResult); // μΆλ ₯: 8
3. λ©μλ μ€λ²λ‘λ©(Method Overloading)
λ©μλ μ€λ²λ‘λ©(Method Overloading)μ μλ°μμ ν ν΄λμ€ λ΄μμ λμΌν μ΄λ¦μ κ°μ§ λ©μλλ₯Ό μ¬λ¬ κ° μ μνλ κ²μ λ§ν©λλ€. λ©μλ μ€λ²λ‘λ©μ μ¬μ©νλ©΄ λμΌν μμ μ μννλ λ©μλλ€μ νλμ μ΄λ¦μΌλ‘ κ·Έλ£Ήνν μ μμ΅λλ€. λ©μλ μ€λ²λ‘λ©μ λ€μν 맀κ°λ³μμ μ ν, μμ, κ°μλ₯Ό νμ©νμ¬ λ©μλμ λ€μμ±μ μ¦κ°μν΅λλ€.
public class Calculator {
// μ μ λ κ°λ₯Ό λνλ λ©μλ
public int add(int a, int b) {
return a + b;
}
// μ€μ λ κ°λ₯Ό λνλ λ©μλ
public double add(double a, double b) {
return a + b;
}
// μ μ μΈ κ°λ₯Ό λνλ λ©μλ
public int add(int a, int b, int c) {
return a + b + c;
}
}
A method is a block of code that performs a specific task, which define the behavior of objects.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
15 Inheritance (0) | 2024.01.20 |
---|---|
14 Encapsulation (feat. Access modifier) (0) | 2024.01.20 |
12 Constructor (0) | 2024.01.19 |
11 Class intro - feat. Field (Member variable) (0) | 2024.01.19 |
10 Object-Oriented Programming (feat. Procedural Programming) (1) | 2024.01.19 |
λκΈ