본문 바로가기
728x90
반응형

다형성(Polymorphism)은 객체 지향 프로그래밍의 핵심 원칙 중 하나로, 한 타입의 참조 변수로 여러 타입의 객체를 참조할 수 있게 하는 특성을 말한다. 다형성을 통해 코드의 유연성을 높이고, 확장성을 향상시킬 수 있다. 

 

아래 코드를 통해 한 타입의 변수로 여러 타입의 객체를 다루는 것이 무엇을 말하는지 알아보자.

'Animal' 타입의 변수를 사용하여 'Dog'와 'Cat' 객체를 모두 참조할 수 있다. 

public interface Animal {
    void sound();
}

public class Dog implements Animal {
    public void sound() {
        System.out.println("The dog barks");
    }
}

public class Cat implements Animal {
    public void sound() {
        System.out.println("The cat meows");
    }
}

Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound();  // 출력: The dog barks
myCat.sound();  // 출력: The cat meows

 

728x90
반응형