Menu
CoddyTech

Basic Inheritance

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 15 of 65.

Inheritance lets one class take over the variables and methods of another. The class that passes them on is the parent, and the class that receives them is the child.

Here is a parent class in its own file:

# animal.gd
class_name Animal
extends RefCounted

var animal_name: String

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

func info() -> void:
	print("I am ", animal_name, ", an animal")

A child class names its parent after extends. The parent's class_name is global, so dog.gd needs no import line:

# dog.gd
class_name Dog
extends Animal

This Dog has no code of its own, yet it has animal_name, info() and the constructor of Animal:

var creature := Animal.new("Creature")
var buddy := Dog.new("Buddy")
creature.info()
buddy.info()
I am Creature, an animal
I am Buddy, an animal

A child can add methods of its own next to the inherited ones. Inside them, the inherited variables work as if the child had declared them:

# dog.gd
class_name Dog
extends Animal

func bark() -> void:
	print(animal_name, " says Woof!")
var buddy := Dog.new("Buddy")
buddy.info()
buddy.bark()
I am Buddy, an animal
Buddy says Woof!

Inheritance goes one way. An Animal does not get what Dog adds, so calling bark() on an Animal object is an error.

The classes you wrote so far said extends RefCounted: they were children of RefCounted, a class built into Godot.

challenge icon

Challenge

Easy

Build a parent class and a child class.

  • In vehicle.gd, give Vehicle two String variables, brand and model. The constructor stores its two arguments in them, and info() returns Vehicle: BRAND MODEL.
  • car.gd already says extends Vehicle. Write its method honk(): it returns BRAND MODEL says Beep beep!, using the variables Car inherits.

Car needs no constructor: Car.new("Honda", "Civic") uses the one from Vehicle.

The supplied code reads how many vehicles follow, then one line per vehicle: vehicle or car, a brand and a model. It prints info() for every vehicle and also honk() for a car. For vehicle Toyota Corolla and car Honda Civic it prints:

Vehicle: Toyota Corolla
Vehicle: Honda Civic
Honda Civic says Beep beep!

Your code goes in vehicle.gd and car.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] == "car":
			var car := Car.new(parts[1], parts[2])
			print(car.info())
			print(car.honk())
		else:
			var vehicle := Vehicle.new(parts[1], parts[2])
			print(vehicle.info())
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