μμ±μ(Constructor)λ κ°μ²΄λ₯Ό μμ±ν λ νΈμΆλλ νΉλ³ν λ©μλλ‘, κ°μ²΄μ μ΄κΈ°νλ₯Ό λ΄λΉν©λλ€. μμ±μλ ν΄λμ€ μ΄λ¦κ³Ό λμΌνλ©°, κ°μ²΄λ₯Ό μμ±ν λ new ν€μλμ ν¨κ» νΈμΆλ©λλ€. μλ°μμλ μμ±μμ μ΄λ¦ μμ λ°ν νμ μ λͺ μνμ§ μμ΅λλ€.
μμ±μμ μ£Όμ λͺ©μ μ κ°μ²΄κ° λ©λͺ¨λ¦¬μ ν λΉλκ³ μΈμ€ν΄μ€ λ³μλ€μ΄ μ΄κΈ°νλ λ νμν μμ μ μννλ κ²μ λλ€. κ°μ²΄λ₯Ό μμ±ν λλ§λ€ μ€νλλ©°, μμ±μλ₯Ό ν΅ν΄ κ°μ²΄μ μ΄κΈ° μνλ₯Ό μ€μ ν μ μμ΅λλ€.
public class Car {
// μΈμ€ν΄μ€ λ³μ
String brand;
int year;
// 맀κ°λ³μκ° μλ μμ±μ
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
// 맀κ°λ³μκ° μλ μμ±μ (κΈ°λ³Έ μμ±μ)
public Car() {
// κΈ°λ³Έ μμ±μ λ΄μ©
}
}
μμ μ½λμμ Car ν΄λμ€λ λ κ°μ μμ±μλ₯Ό κ°μ§κ³ μμ΅λλ€. 첫 λ²μ§Έ μμ±μλ 맀κ°λ³μλ₯Ό λ°μμ κ°μ²΄λ₯Ό μ΄κΈ°ννκ³ , λ λ²μ§Έ μμ±μλ 맀κ°λ³μ μμ΄ κ°μ²΄λ₯Ό μ΄κΈ°νν©λλ€. μμ±μλ₯Ό λͺ μμ μΌλ‘ μ μΈνμ§ μμ κ²½μ°, μλ°λ κΈ°λ³Έ μμ±μλ₯Ό μλμΌλ‘ μμ±ν©λλ€.
μμ±μ μ€λ²λ‘λ©(Constructor Overloading)
νλμ ν΄λμ€ λ΄μμ λμΌν μ΄λ¦μ μμ±μλ₯Ό μ¬λ¬ κ° μ μνλ κ²μ λ§ν©λλ€. μμ±μ μ€λ²λ‘λ©μ ν΅ν΄ κ°μ μ΄λ¦μ μμ±μλ₯Ό λ€μν 맀κ°λ³μλ₯Ό λ°μμ νΈμΆν μ μμΌλ©°, μ΄λ₯Ό ν΅ν΄ κ°μ²΄λ₯Ό λ€μν λ°©μμΌλ‘ μ΄κΈ°νν μ μμ΅λλ€.
thisμ this()
μμ±μμμ μ¬μ©λλ ν€μλλ‘, κ°μ²΄μ μΈμ€ν΄μ€λ₯Ό λνλ΄λ λ° μ¬μ©λ©λλ€. κ·Έλ¬λ λ ν€μλ κ°μλ λͺ κ°μ§ μ€μν μ°¨μ΄μ μ΄ μμ΅λλ€.
1) this: νμ¬ κ°μ²΄μ μ°Έμ‘°λ₯Ό λνλ λλ€. μ£Όλ‘ μΈμ€ν΄μ€ λ³μμ λ©μλμ 맀κ°λ³μ μ΄λ¦μ΄ κ°μ λ, μΈμ€ν΄μ€ λ³μλ₯Ό κ°λ¦¬ν€κΈ° μν΄ μ¬μ©λ©λλ€.
2) this(): κ°μ ν΄λμ€μ λ€λ₯Έ μμ±μλ₯Ό νΈμΆνλ λ° μ¬μ©λ©λλ€.
- λ°λμ 첫 λ²μ§Έ λ¬Έμ₯μΌλ‘λ§ μ¬μ©λ μ μμ΅λλ€.
- ν μμ±μμμ λ€λ₯Έ μμ±μλ₯Ό νΈμΆνμ¬ μ½λμ μ€λ³΅μ λ°©μ§νκ³ , μ΄κΈ°ν μ½λλ₯Ό μ¬μ¬μ©ν μ μμ΅λλ€.
Constructors are special methods used to initialize objects of a class.
Constructor overloading refer to have multiple constructors with different parameter lists. Each constructor provides a different way to create an object of the class by accepting different sets of arguments.
The 'this' keyword this refers to the current instance of the class.
'this()' is a special keyword that refers to the current class's constructor. It is used within a constructor to invoke another constructor of the same class.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
14 Encapsulation (feat. Access modifier) (0) | 2024.01.20 |
---|---|
13 Method (0) | 2024.01.20 |
11 Class intro - feat. Field (Member variable) (0) | 2024.01.19 |
10 Object-Oriented Programming (feat. Procedural Programming) (1) | 2024.01.19 |
9 Two-dimensional Arrays (Feat. Object Array) (0) | 2024.01.19 |
λκΈ