Method Overriding Revisited
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 21 of 65.
Polymorphism means "many forms": one method call does different things depending on the class of the object that receives it. Overriding is what makes this work.
# animal.gd
class_name Animal
extends RefCounted
func speak() -> String:
return "..."# dog.gd
class_name Dog
extends Animal
func speak() -> String:
return "Woof!"# cat.gd
class_name Cat
extends Animal
func speak() -> String:
return "Meow!"An Array[Animal] can hold all of them. The loop calls speak() without knowing which class each element has, and every object answers with its own version:
var animals: Array[Animal] = [Dog.new(), Cat.new(), Animal.new()]
for animal in animals:
print(animal.speak())Woof!
Meow!
...A function with an Animal parameter works the same way. It accepts every child class, including classes you add later, without a change:
func make_it_speak(animal: Animal) -> void:
print("It says ", animal.speak())make_it_speak(Cat.new())It says Meow!Compare this with checking classes one by one. A chain of if animal is Dog: branches must grow with every new class. With overriding, each class carries its own behavior, and the code that calls it stays the same.
Challenge
EasyA garage handles every vehicle through one Array[Vehicle]. In vehicle.gd, wheels() returns 0 and sound() returns ....
- Write
describe()inVehicle. It returnsBRAND: N wheels, SOUND, callingwheels()andsound(). Caroverrideswheels()with4andsound()withVroom.Motorcycleoverrides them with2andBrrm.Truckalready stores its number oftrailers. It overrideswheels()with6plus4per trailer, andsound()withHonk.
The children do not override describe(). The supplied code reads how many vehicles follow, then one line per vehicle: car BRAND, motorcycle BRAND, truck BRAND TRAILERS or vehicle BRAND. It prints every describe() and the total of wheels(). For car Toyota and truck Volvo 2 it prints:
Toyota: 4 wheels, Vroom
Volvo: 14 wheels, Honk
Total wheels: 18Your code goes in vehicle.gd, car.gd, motorcycle.gd and truck.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())
var vehicles: Array[Vehicle] = []
for i in count:
var p := OS.read_string_from_stdin().split(" ")
if p[0] == "car":
vehicles.append(Car.new(p[1]))
elif p[0] == "motorcycle":
vehicles.append(Motorcycle.new(p[1]))
elif p[0] == "truck":
vehicles.append(Truck.new(p[1], int(p[2])))
else:
vehicles.append(Vehicle.new(p[1]))
var total := 0
for v in vehicles:
print(v.describe())
total += v.wheels()
print("Total wheels: %d" % total)
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