Inner Classes
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 41 of 65.
A class can declare another class inside it, with the keyword class, a name and an indented body. This inner class is a helper type that belongs to the outer one:
# inventory.gd
class_name Inventory
extends RefCounted
const MAX_STACK := 5
class Slot:
var item_name: String
var count: int
func _init(new_name: String, new_count: int) -> void:
item_name = new_name
count = mini(new_count, MAX_STACK)
func _to_string() -> String:
return "%s x%d" % [item_name, count]
var slots: Array[Slot] = []
func add(item_name: String, count: int) -> Slot:
var slot := Slot.new(item_name, count)
slots.append(slot)
return slotInside inventory.gd, the inner class is Slot. Every other file reaches it through the outer class: Inventory.Slot.
# main.gd
var bag := Inventory.new()
bag.add("Potion", 9)
var arrows: Inventory.Slot = bag.add("Arrow", 3)
print(bag.slots) # [Potion x5, Arrow x3]
var gem := Inventory.Slot.new("Gem", 1)An inner class without extends extends RefCounted, and it can have variables, a constructor and methods like any class. It can use the outer class's constants and enums (MAX_STACK above), but not its member variables: Slot has no access to slots, because a slot is a separate object. Pass any value it needs to its constructor.
Use an inner class for a small type that only makes sense together with its outer class, such as a slot of an inventory or an entry of a score table. A type that other parts of the game use on its own deserves its own file and class_name.
Challenge
EasyBuild a Leaderboard whose entries are an inner class.
- Declare the inner class
EntryinsideLeaderboard, withplayer_nameandscoreset by its constructor, and_to_string()returningAda: 120. entriesis a typed array ofEntry, in the order players first appear.submit(player, score)adds a new entry for a new player. For a player who already has an entry, it keeps the higher of the two scores.best()returns the entry with the highest score. On a tie, the entry that appears first wins.
The supplied code reads how many scores follow (Ada 120), submits them, then prints every entry and the best one (at least one score is always given). For Ada 120, Bo 90, Ada 80, Bo 150, Cy 150 it prints:
Ada: 120
Bo: 150
Cy: 150
Best: Bo: 150Your code goes in leaderboard.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 board := Leaderboard.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
board.submit(parts[0], int(parts[1]))
for entry in board.entries:
print(entry)
print("Best: ", board.best())
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