🐍 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λ₯Ό ν™œμš©ν•˜λ©΄ 더 μœ μ—°ν•œ ꡬ쑰 섀계도 κ°€λŠ₯ν•˜μ£ .

μ½”λ©˜νŠΈ

λ‹΅κΈ€ 남기기

이메일 μ£Όμ†ŒλŠ” κ³΅κ°œλ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. ν•„μˆ˜ ν•„λ“œλŠ” *둜 ν‘œμ‹œλ©λ‹ˆλ‹€