
π‘λ€νμ±(Polymorphism) μ΄λ?
λ€νμ±μ κ°λ
- νλμ κ°μ²΄κ° μ¬λ¬ κ°μ§ νμ μ κ°μ§ μ μλ κ²μ μλ―Έ. μ¦, λ€νμ±μ νμ©νλ©΄ λΆλͺ¨ ν΄λμ€κ° μμν΄λμ€μ λμ λ°©μμ μ μ μμ΄λ μ€λ²λΌμ΄λ©μ ν΅ν΄ μμ ν΄λμ€λ₯Ό μ κ·Όν μ μλ€.
- μμ κ΄κ³μμ ꡬν κ°λ₯
- μ 보μλ, μμκ³Ό λλΆμ΄ κ°μ²΄μ§ν₯ νλ‘κ·Έλλ°μ κ°μ₯ ν° νΉμ§ μ€ νλ
- κ°μ²΄μ§ν₯ νλ‘κ·Έλλ°μ μ μ°μ±, μ¬νμ©μ±, μ μ§λ³΄μμ±μ κΈ°λ³Έμ΄ λλ νΉμ§
- μμ ν΄λμ€λ₯Ό λΆλͺ¨ ν΄λμ€ νμ μΌλ‘ κ°μ²΄λ₯Ό μ μΈνλ©΄ μμ ν΄λμ€μ λ©μλκ° μ€νλ¨.
- λΆλͺ¨ ν΄λμ€λ₯Ό μμ ν΄λμ€ νμ μΌλ‘ κ°μ²΄λ₯Ό μ μΈν μ μμ.
λ€νμ± μμ
class Person {
void print() {
System.out.println("Personν΄λμ€μ print()λ©μλ");
}
}
class Student extends Person {
@Override
public void print() {
System.out.println("Studentν΄λμ€μ print()λ©μλ");
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person(); //μΌλ°μ μΈ κ°μ²΄ μ μΈ
Student st1 = new Student(); //μΌλ°μ μΈ κ°μ²΄ μ μΈ
Person p2 = new Student(); // λΆλͺ¨ κ°μ²΄λ‘ μμ κ°μ²΄ μ μΈ κ°λ₯
// Student st2 = new Person(); // μμ κ°μ²΄λ‘ λΆλͺ¨ κ°μ²΄ μ μΈ λΆκ°
p1.print();
st1.print();
p2.print();
}
}
<μΆλ ₯ κ²°κ³Ό>
Personν΄λμ€μ print()λ©μλ
Studentν΄λμ€μ print()λ©μλ
Studentν΄λμ€μ print()λ©μλ
instanceof μ°μ°μ
- λ€νμ±μΌλ‘ μΈν΄ λ°νμμ μ°Έμ‘° λ³μκ° μ€μ λ‘ μ°Έμ‘°νκ³ μλ μΈμ€ν΄μ€ νμ μ νμΈν μμ μ¬μ©.
- [μ°Έμ‘°λ³μ] instance of [ν΄λμ€μ΄λ¦] λ¬Έλ²μ μ¬μ©νλ©°, μΌμͺ½μ μ λ¬λ μ°Έμ‘° λ³μκ° μ€μ λ‘ μ°Έμ‘°νκ³ μλ μΈμ€ν΄μ€μ νμ μ΄ μ€λ₯Έμͺ½μ μ λ¬λ ν΄λμ€ νμ μ΄λ©΄ true, μλλ©΄ falseλ₯Ό λ°ννλ€.
class Person {
void print() {
System.out.println("Personν΄λμ€μ print()λ©μλ");
}
}
class Student extends Person {
@Override
public void print() {
System.out.println("Studentν΄λμ€μ print()λ©μλ");
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person(); //μΌλ°μ μΈ κ°μ²΄ μ μΈ
Student st1 = new Student(); //μΌλ°μ μΈ κ°μ²΄ μ μΈ
Person p2 = new Student(); // λΆλͺ¨ κ°μ²΄λ‘ μμ κ°μ²΄ μ μΈ κ°λ₯
// Student st2 = new Person(); // μμ κ°μ²΄λ‘ λΆλͺ¨ κ°μ²΄ μ μΈ λΆκ°
System.out.println("p1");
System.out.println(p1 instanceof Object);
System.out.println(p1 instanceof Person);
System.out.println(p1 instanceof Student);
System.out.println("p2");
System.out.println(p2 instanceof Object);
System.out.println(p2 instanceof Person);
System.out.println(p2 instanceof Student);
}
}
<μΆλ ₯ κ²°κ³Ό>
p1
true
true
false
p2
true
true
true
πReference
http://www.tcpschool.com/java/java_polymorphism_concept
https://life-with-coding.tistory.com/485
ν΄λΉ κΈμ νμ΅ν λ΄μ©μ κ°μΈμ μΌλ‘ μ 리ν κΈμ λλ€. λ§μ½ νλ¦° λΆλΆμ΄ μλ€λ©΄ λκΈλ‘ λ¨κ²¨μ£ΌμΈμ:D