Swift '문법'
클래스 상속
김동준.
2024. 7. 17. 23:21
클래스 상속은 객체 지향 프로그래밍(OOP)에서 중요한 개념 중 하나로, 기존 클래스의 속성과 메서드를 새로운 클래스가 물려받아 재사용할 수 있게 해주는 기능입니다. 이를 통해 코드의 재사용성을 높이고, 유지보수를 용이하게 합니다. 상속을 이해하기 위해 기본 용어와 예제를 소개하겠습니다.
기본 용어
부모 클래스(또는 슈퍼 클래스,상위클래스):다른 클래스에게 속성과 메서드를 물려주는 클래스입니다.
자식클래스(또는 서브 클래스,하위클래스):부모클래스로부터 속성과 메서드를 물려받는 클래스입니다.
class ParentClass:
# 부모 클래스의 생성자
def __init__(self, value):
self.value = value
# 부모 클래스의 메서드
def display(self):
print(f"Value: {self.value}")
# 자식 클래스는 부모 클래스를 상속받음
class ChildClass(ParentClass):
# 자식 클래스의 생성자
def __init__(self, value, child_value):
# 부모 클래스의 생성자 호출
super().__init__(value)
self.child_value = child_value
# 자식 클래스의 추가 메서드
def display_child(self):
print(f"Child Value: {self.child_value}")
# 부모 클래스 인스턴스 생성 및 메서드 호출
parent_instance = ParentClass(10)
parent_instance.display() # 출력: Value: 10
# 자식 클래스 인스턴스 생성 및 메서드 호출
child_instance = ChildClass(20, 30)
child_instance.display() # 출력: Value: 20
child_instance.display_child() # 출력: Child Value: 30
주요 특징
코드재사용성:자식 클래스는 부모 클래스의 속성과 메서드를 물려받아 그대로 사용할 수 있습니다.
메서드 오버라이딩:자식 클래스는 부모 클래스의 메서드를 재정의할 수 있습니다. 이를 통해 자식 클래스에서 부모 클래스의 동작을 변경할 수 있습니다.
class ParentClass:
def greet(self):
print("Hello from ParentClass")
class ChildClass(ParentClass):
def greet(self):
print("Hello from ChildClass")
# 인스턴스 생성 및 메서드 호출
parent_instance = ParentClass()
parent_instance.greet() # 출력: Hello from ParentClass
child_instance = ChildClass()
child_instance.greet() # 출력: Hello from ChildClass
이처럼 상속을 사용하면 객체 지향 프로그래밍의 장점을 극대화할 수 있으며, 코드의 재사용성과 유지보수성을 높일 수 있습니다.