κ°λ°μ νλ€ λ³΄λ©΄ κ°μ²΄μ§ν₯ νλ‘κ·Έλλ°μ ν΅μ¬ κ°λ μΈ μμκ³Ό λ€νμ±, κ·Έλ¦¬κ³ μΆμ ν΄λμ€λ₯Ό μμ£Ό μ νκ² λ©λλ€. μ΄λ² ν¬μ€ν μμλ 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(); // λ€νμ±
}
}
}
π ν΅μ¬ λΉκ΅ μμ½
κ°λ | Python | Java |
---|---|---|
μΆμ ν΄λμ€ | raise NotImplementedError() | abstract class , abstract method |
μμ±μ | __init__ λ©μλ | ν΄λμ€λͺ κ³Ό λμΌν μμ±μ λ©μλ |
λ€νμ± κ΅¬ν | λΆλͺ¨ ν΄λμ€ λ¦¬μ€νΈμ μμ κ°μ²΄ μ μ₯ | λΆλͺ¨ ν΄λμ€ λ°°μ΄ λλ 리μ€νΈ μ¬μ© |
μμΈ μ²λ¦¬ | try + except NotImplementedError | try + catch (UnsupportedOperationException λ±) |
β μ 리
- Pythonμ
NotImplementedError
λ₯Ό ν΅ν΄ μΆμ λ©μλλ₯Ό κ°μ νλ©°, μ μ°ν ꡬ쑰λ₯Ό κ°μ§ - Javaλ λͺ
νν
abstract
ν€μλλ₯Ό ν΅ν΄ μ»΄νμΌ νμμ λ©μλ ꡬν μ¬λΆλ₯Ό 체ν¬ν¨ - λ μΈμ΄ λͺ¨λ **λ€νμ±(polymorphism)**μ ν΅ν΄ μμ ν΄λμ€μ νλμ λμ μΌλ‘ μ²λ¦¬ κ°λ₯
π§ μ€μ ν:
- Pythonμμλ ABC(Abstract Base Class) λͺ¨λμ νμ©νλ©΄ Javaμ²λΌ λ μ격ν μΆμ ν΄λμ€λ₯Ό λ§λ€ μ μμ΄μ!
- Javaμμλ μΆμ ν΄λμ€ λμ
interface
λ₯Ό νμ©νλ©΄ λ μ μ°ν ꡬ쑰 μ€κ³λ κ°λ₯νμ£ .
λ΅κΈ λ¨κΈ°κΈ°