Method Overriding
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 17 of 65.
A child overrides a method by defining a method with the same name. Objects of the child class then run the child's version, and the methods it does not override are still inherited unchanged.
# 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 BuddyThe override must keep the parent's signature: the same parameters and the same return type. With a different one, the program does not start:
# 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".The child's version runs even when the call comes from a method of the parent. Here introduce() exists only in Animal, and it calls sound(), which Cat overrides:
# 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 MeowVariables cannot be overridden: declaring var animal_name again in Dog is a parse error (The member "animal_name" already exists in parent class Animal). To give a child a different starting value, assign it in the child's _init().
Challenge
Easyshape.gd holds the finished Shape class: a color, area() returning 0.0 and describe(). Circle and Square extend it and already have their constructors. Override two methods in each:
Circle:area()returnsPI * radius * radius, anddescribe()returnsThis is a COLOR circle with radius R.Square:area()returnsside * side, anddescribe()returnsThis is a COLOR square with side S.
Keep the parent's signatures: func area() -> float and func describe() -> String.
The supplied code reads how many shapes follow, then one line per shape: shape COLOR, circle COLOR RADIUS or square COLOR SIDE. It prints describe() and the area with two decimals. For circle red 5 and shape green it prints:
This is a red circle with radius 5
Area: 78.54
This is a green shape
Area: 0.00Your code goes in circle.gd and square.gd. main.gd holds the supplied input/output code and cannot be edited.
Try it yourself
extends Node
func _ready():
# Supplied input/output code: keep it as it is
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())
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler