Menu
CoddyTech

메서드 오버라이딩

Coddy GDScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 65개 중 17번째.

자식 클래스는 같은 이름의 메서드를 정의하여 메서드를 재정의합니다. 그러면 자식 클래스의 객체는 자식 클래스의 버전을 실행하고, 재정의하지 않은 메서드는 변경되지 않은 채 계속 상속됩니다.

# animal.gd
class_name Animal
extends RefCounted

var animal_name: String

func _init(n: String) -> void:
	animal_name = n

func make_sound() -> void:
	print("Some generic animal sound")

func info() -> void:
	print("I am ", animal_name)
# dog.gd
class_name Dog
extends Animal

func make_sound() -> void:
	print("Woof! Woof!")
var animal := Animal.new("Generic")
var dog := Dog.new("Buddy")
animal.make_sound()
dog.make_sound()
dog.info()
Some generic animal sound
Woof! Woof!
I am Buddy

오버라이드는 부모의 시그니처를 유지해야 합니다. 즉, 매개변수와 반환 유형이 동일해야 합니다. 다르게 작성하면 프로그램이 시작되지 않습니다:

# animal.gd
func speak(times: int) -> String:
	return "...".repeat(times)
# dog.gd
func speak() -> String:
	return "Woof"
Parse Error: The function signature doesn't match the parent. Parent signature is "speak(int) -> String".

메서드 호출이 부모 클래스의 메서드에서 시작되더라도 자식 클래스의 버전이 실행됩니다. 여기서 introduce()는 Animal에만 있으며, Cat이 재정의하는 sound()를 호출합니다:

# animal.gd
func sound() -> String:
	return "..."

func introduce() -> String:
	return animal_name + " says " + sound()
# cat.gd
func sound() -> String:
	return "Meow"
print(Cat.new("Tom").introduce())
Tom says Meow

변수는 재정의할 수 없습니다. Dog에서 var animal_name을 다시 선언하면 구문 분석 오류가 발생합니다(The member "animal_name" already exists in parent class Animal). 자식에 다른 초기값을 지정하려면 자식의 _init()에서 할당하세요.

challenge icon

챌린지

쉬움

shape.gd에는 완성된 Shape 클래스가 들어 있습니다. 이 클래스에는 color, 0.0을 반환하는 area(), describe()가 있습니다. Circle과 Square는 이를 확장하며 생성자도 이미 작성되어 있습니다. 각 클래스에서 메서드 두 개를 재정의하세요.

  • Circle: area()는 PI * radius * radius를 반환하고, describe()는 This is a COLOR circle with radius R를 반환합니다.
  • Square: area()는 side * side를 반환하고, describe()는 This is a COLOR square with side S를 반환합니다.

부모 클래스의 시그니처를 그대로 유지하세요: func area() -> float 및 func describe() -> String.

제공된 코드는 뒤따르는 도형의 개수를 읽은 다음, 도형마다 한 줄씩 읽습니다: shape COLOR, circle COLOR RADIUS 또는 square COLOR SIDE. describe()와 소수점 이하 두 자리로 표시한 넓이를 출력합니다. circle red 5와 shape green을 입력하면 다음을 출력합니다.

This is a red circle with radius 5
Area: 78.54
This is a green shape
Area: 0.00

코드는 circle.gd와 square.gd에 작성하세요. main.gd에는 제공된 입출력 코드가 들어 있으며 수정할 수 없습니다.

직접 해보기

extends Node

func _ready():
	# 제공된 입력/출력 코드: 그대로 유지하세요
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var shape: Shape
		if parts[0] == "circle":
			shape = Circle.new(parts[1], int(parts[2]))
		elif parts[0] == "square":
			shape = Square.new(parts[1], int(parts[2]))
		else:
			shape = Shape.new(parts[1])
		print(shape.describe())
		print("Area: %.2f" % shape.area())
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 GDScript 컴파일러