다형성 활용 - 문제 인식

package poly.ex1;

public class AnimalSoundMain {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        Caw caw = new Caw();

        System.out.println("동물 소리 테스트 시작");
        dog.sound();
        System.out.println("동물 소리 테스트 종료");

        System.out.println("동물 소리 테스트 시작");
        cat.sound();
        System.out.println("동물 소리 테스트 종료");

        System.out.println("동물 소리 테스트 시작");
        caw.sound();
        System.out.println("동물 소리 테스트 종료");

    }
}

→ 다음과 같은 코드를 사용할때에 동물이 늘어나거나 줄어들때에 계속 코드를 수정 해주어야 한다.

System.out.println("동물 소리 테스트 시작");
caw.sound();
System.out.println("동물 소리 테스트 종료");

→ 코드를 보면 이런 형식이 반복 되는것을 볼 수 있다.

→ for문을 돌릴 수도 있지만 Dog, Cat, Caw 의 클래스가 다 다른 클래스 이어서 문제가 발생한다.

→ 이럴때 상속과 다형성, 메서드 오버라이딩을 사용하면 된다.


다형성 사용 - 다형성으로 문제 풀기

다형성을 사용하기 위해 위와 같은 상속 관계를 만들어 줄 것이다.

  1. animal 에서 sound 기능을 생성해주고
  2. 각각 dog, cat, caw 가 상속을 받고 sound 기능을 오버라이딩하여 사용할 것 이다.

⇒ 다형적 참조와 메서드 오버라이딩 덕분에 여러줄의 코드 추가 없이 간단하게 재사용하여 해결 할 수 있다.


다형성 활용3

→ 다형적 참조와 메서드 오버라이딩 한 코드를 배열과 for 문을 사용하여 중복을 제거해보자

package poly.ex2;

public class AnimalPolyMain2 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        Caw caw = new Caw();
        Animal[] animalArr = {dog, cat, caw};
        // Dog, Cat, Caw 모두 Animal 타입 이기때문에 받을수 있다
        for (Animal animal : animalArr) {
            System.out.println("동물 소리 테스트 시작");
            animal.sound();
            System.out.println("동물 소리 테스트 종료");
        }
        // 배열을 순회하면서 오버라이딩 메서드도 호출 된다.
    }
}

→ 더 간단하게 다음과 같이 만들 수 있다.

package poly.ex2;

public class AnimalPolyMain3 {
    public static void main(String[] args) {
        Animal[] animalArr = {new Dog(), new Cat(), new Caw()};

        for (Animal animal : animalArr) {
            soundAnimal(animal);
        }
    }

    // 변하지 않는 부분
    private static void soundAnimal(Animal animal) {
        System.out.println("동물 소리 테스트 시작");
        animal.sound();
        System.out.println("동물 소리 테스트 종료");
    }
}


+ Recent posts