The super Keyword
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 16 of 65.
When a child needs extra data, it writes its own _init(). The parent's constructor then no longer runs by itself. Call it with super(), passing the arguments the parent expects:
# animal.gd
class_name Animal
extends RefCounted
var animal_name: String
func _init(n: String) -> void:
animal_name = n
print("Animal created: ", n)# dog.gd
class_name Dog
extends Animal
var breed: String
func _init(n: String, b: String) -> void:
super(n)
breed = b
print("Dog breed set: ", b)var buddy := Dog.new("Buddy", "Beagle")
print(buddy.animal_name, " the ", buddy.breed)Animal created: Buddy
Dog breed set: Beagle
Buddy the BeagleWithout the super(n) line the program still runs, but the constructor of Animal is skipped: nothing sets animal_name, so it stays an empty String. Put super() first, so the parent's variables are ready before the child uses them.
In any other method, super() runs the parent's version of the method you are in. The child keeps the parent's result and adds to it:
# animal.gd
func describe() -> String:
return "I am " + animal_name# dog.gd
func describe() -> String:
return super() + ", a " + breedvar rex := Dog.new("Rex", "Husky")
print(rex.describe())Animal created: Rex
Dog breed set: Husky
I am Rex, a HuskyTo call a different parent method, write its name after a dot: super.describe() works from any method of Dog.
Challenge
EasyWrite a Person class and an Employee class that extends it.
Personstoresperson_nameandagein its constructor.introduce()returnsHi, I'm NAME and I'm AGE years old.Employeeaddsjob. Its constructor passes the name and the age tosuper()and stores the job. Itsintroduce()returns the result of the parent'sintroduce()followed by. I work as a JOB.
The supplied code reads how many people follow, then one line per person: person NAME AGE or employee NAME AGE JOB. It prints introduce() for each one. For person Alice 30 and employee Bob 35 Developer it prints:
Hi, I'm Alice and I'm 30 years old
Hi, I'm Bob and I'm 35 years old. I work as a DeveloperYour code goes in person.gd and employee.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(" ")
if parts[0] == "employee":
var employee := Employee.new(parts[1], int(parts[2]), parts[3])
print(employee.introduce())
else:
var person := Person.new(parts[1], int(parts[2]))
print(person.introduce())
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