java oop : message polymorphism
This commit is contained in:
22
JavaOOP/src/Java21.java
Normal file
22
JavaOOP/src/Java21.java
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import myObject.Animal;
|
||||||
|
import myObject.Cat;
|
||||||
|
import myObject.Dog;
|
||||||
|
|
||||||
|
public class Java21 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// 1. 다형성 인수
|
||||||
|
Dog dog = new Dog();
|
||||||
|
Cat cat = new Cat();
|
||||||
|
|
||||||
|
display(dog);
|
||||||
|
display(cat);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void display(Animal animal) { // 다형성 인수 upcasting
|
||||||
|
animal.eat();
|
||||||
|
// Cat 타입 인지 확인 instanceof -> Cat 타입 일때만 실행
|
||||||
|
if (animal instanceof Cat) {
|
||||||
|
((Cat) animal).say(); // downcasting
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
19
JavaOOP/src/Java22.java
Normal file
19
JavaOOP/src/Java22.java
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import myObject.Animal;
|
||||||
|
import myObject.Cat;
|
||||||
|
import myObject.Dog;
|
||||||
|
|
||||||
|
public class Java22 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// 2. 다형성 배열
|
||||||
|
Animal[] animals = new Animal[2];
|
||||||
|
animals[0] = new Dog();
|
||||||
|
animals[1] = new Cat();
|
||||||
|
|
||||||
|
for (Animal animal : animals) {
|
||||||
|
animal.eat();
|
||||||
|
if (animal instanceof Cat) {
|
||||||
|
((Cat) animal).say();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user