๊ฐ๋ฐ์ ํ๋ค ๋ณด๋ฉด ๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ์ ํต์ฌ ๊ฐ๋ ์ธ ์์๊ณผ ๋คํ์ฑ, ๊ทธ๋ฆฌ๊ณ ์ถ์ ํด๋์ค๋ฅผ ์์ฃผ ์ ํ๊ฒ ๋ฉ๋๋ค. ์ด๋ฒ ํฌ์คํ ์์๋ 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
๋ฅผ ํ์ฉํ๋ฉด ๋ ์ ์ฐํ ๊ตฌ์กฐ ์ค๊ณ๋ ๊ฐ๋ฅํ์ฃ .
๋ต๊ธ ๋จ๊ธฐ๊ธฐ