[카테고리:] 미분류

  • 🐍 Python vs ☕ Java: 추상 클래스와 다형성 비교

    개발을 하다 보면 객체지향 프로그래밍의 핵심 개념인 상속다형성, 그리고 추상 클래스를 자주 접하게 됩니다. 이번 포스팅에서는 Python과 Java에서 이 개념들이 어떻게 구현되는지, 두 언어의 차이를 간단한 예제로 비교해보겠습니다.


    🔸 예시 시나리오: 동물이 말을 한다?

    Python 코드

    class Animal:
    def __init__(self, name, age):
    self.name = name
    self.age = age

    def speak(self):
    raise NotImplementedError("Subclasses must implement this method")

    class Dog(Animal):
    def __init__(self, name, age, breed):
    super().__init__(name, age)
    self.breed = breed

    def speak(self):
    print("Woof!")

    class Cat(Animal):
    def __init__(self, name, age, color):
    super().__init__(name, age)
    self.color = color

    def speak(self):
    print("Meow!")

    animals = [
    Animal("Generic Animal", 5),
    Dog("Buddy", 3, "Golden Retriever"),
    Cat("Whiskers", 2, "Gray"),
    ]

    for animal in animals:
    try:
    animal.speak()
    except NotImplementedError:
    print(f"{animal.name} cannot speak (abstract method)")

    Java 코드

    abstract class Animal {
    protected String name;
    protected int age;

    public Animal(String name, int age) {
    this.name = name;
    this.age = age;
    }

    public abstract void speak();
    }

    class Dog extends Animal {
    private String breed;

    public Dog(String name, int age, String breed) {
    super(name, age);
    this.breed = breed;
    }

    @Override
    public void speak() {
    System.out.println("Woof!");
    }
    }

    class Cat extends Animal {
    private String color;

    public Cat(String name, int age, String color) {
    super(name, age);
    this.color = color;
    }

    @Override
    public void speak() {
    System.out.println("Meow!");
    }
    }

    public class Main {
    public static void main(String[] args) {
    Animal[] animals = {
    new Dog("Buddy", 3, "Golden Retriever"),
    new Cat("Whiskers", 2, "Gray")
    };

    for (Animal animal : animals) {
    animal.speak(); // 다형성
    }
    }
    }

    🔍 핵심 비교 요약

    개념PythonJava
    추상 클래스raise NotImplementedError()abstract class, abstract method
    생성자__init__ 메서드클래스명과 동일한 생성자 메서드
    다형성 구현부모 클래스 리스트에 자식 객체 저장부모 클래스 배열 또는 리스트 사용
    예외 처리try + except NotImplementedErrortry + catch (UnsupportedOperationException 등)

    ✅ 정리

    • Python은 NotImplementedError를 통해 추상 메서드를 강제하며, 유연한 구조를 가짐
    • Java는 명확한 abstract 키워드를 통해 컴파일 타임에 메서드 구현 여부를 체크함
    • 두 언어 모두 **다형성(polymorphism)**을 통해 자식 클래스의 행동을 동적으로 처리 가능

    🔧 실전 팁:

    • Python에서는 ABC(Abstract Base Class) 모듈을 활용하면 Java처럼 더 엄격한 추상 클래스를 만들 수 있어요!
    • Java에서는 추상 클래스 대신 interface를 활용하면 더 유연한 구조 설계도 가능하죠.