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 AnimalThis 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 animalA 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
EasyBuild a parent class and a child class.
- In
vehicle.gd, giveVehicletwo String variables,brandandmodel. The constructor stores its two arguments in them, andinfo()returnsVehicle: BRAND MODEL. car.gdalready saysextends Vehicle. Write its methodhonk(): it returnsBRAND MODEL says Beep beep!, using the variablesCarinherits.
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())
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