Menu
CoddyTech

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 Beagle

Without 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 " + breed
var rex := Dog.new("Rex", "Husky")
print(rex.describe())
Animal created: Rex
Dog breed set: Husky
I am Rex, a Husky

To call a different parent method, write its name after a dot: super.describe() works from any method of Dog.

challenge icon

Challenge

Easy

Write a Person class and an Employee class that extends it.

  • Person stores person_name and age in its constructor. introduce() returns Hi, I'm NAME and I'm AGE years old.
  • Employee adds job. Its constructor passes the name and the age to super() and stores the job. Its introduce() returns the result of the parent's introduce() 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 Developer

Your 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())
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler