λ€νμ±(Polymorphism)μ κ°μ²΄ μ§ν₯ νλ‘κ·Έλλ°(OOP)μμμ μ€μν κ°λ μ€ νλλ‘, λμΌν μ½λκ° μ¬λ¬ νμ μ κ°μ²΄μμ λ€λ₯΄κ² λμν μ μλ λ₯λ ₯μ μλ―Έν©λλ€.
λ€νμ±μ μ½λμ μ μ°μ±μ λμ΄κ³ κ°μ²΄ κ°μ κ΄κ³λ₯Ό κ°κ²°νκ² νννλ λ° κΈ°μ¬ν©λλ€.
- λΆλͺ¨ νμ μΌλ‘ μμ νμ μ κ°μ²΄ μ°Έμ‘° κ°λ₯ (리λͺ¨μ»¨ κ°μκ° μμΌλκΉ)
- μμ νμ μΌλ‘ λΆλͺ¨ νμ κ°μ²΄ μ°Έμ‘° λΆκ°λ₯ (리λͺ¨μ»¨ κ°μκ° λ§μΌλκΉ)
// λ€νμ± - μ¬λ¬κ°μ§ ννλ₯Ό κ°μ§ μ μλ λ₯λ ₯
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal dog = new Dog(); // λ°λλ‘ μμμ΄ λΆλͺ¨ κ°μ²΄λ₯Ό μ°Έμ‘°ν μλ μλ€
Animal cat = new Cat(); // μμ κ°μ²΄κ° 리λͺ¨μ»¨ κ°μκ° λ§κΈ° λλ¬Έ
dog.sound();
cat.sound();
}
}
instanceof μ°μ°μ
instanceofλ Javaμ κ°μ κ°μ²΄ μ§ν₯ νλ‘κ·Έλλ° μΈμ΄μμ μ¬μ©λλ μ°μ°μ μ€ νλλ‘, κ°μ²΄μ νμ μ νμΈνλ λ°μ μ°μ λλ€. μ΄ μ°μ°μλ νΉμ κ°μ²΄κ° νΉμ ν΄λμ€μ μΈμ€ν΄μ€μΈμ§ λλ νΉμ μΈν°νμ΄μ€λ₯Ό ꡬνν κ°μ²΄μΈμ§ νμΈνλ λ° μ¬μ©λ©λλ€.
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class InstanceOfExample {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
System.out.println(myDog instanceof Animal); // true
System.out.println(myDog instanceof Dog); // true
System.out.println(myDog instanceof Cat); // false
System.out.println(myCat instanceof Animal); // true
System.out.println(myCat instanceof Dog); // false
System.out.println(myCat instanceof Cat); // true
}
}
μμ μμ μμ instanceof μ°μ°μλ₯Ό μ¬μ©νμ¬ κ°μ²΄κ° μ΄λ€ ν΄λμ€μ μΈμ€ν΄μ€μΈμ§ νμΈνκ³ μμ΅λλ€. μ΄ μ°μ°μλ₯Ό μ¬μ©νλ©΄ μ€ν μ€μ κ°μ²΄μ νμ μ λμ μΌλ‘ νμΈν μ μμΌλ©°, μ΄λ λ€νμ±κ³Ό κ΄λ ¨λ μ½λμμ μ μ©νκ² νμ©λ©λλ€.
νλ³ν κ·μΉ
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference refer to a child class object.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
20 Exceptions (0) | 2024.01.21 |
---|---|
19 Interface (0) | 2024.01.20 |
17 Abstraction (0) | 2024.01.20 |
16 Composition relationship (0) | 2024.01.20 |
15 Inheritance (0) | 2024.01.20 |
λκΈ