Introduction to OOP
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 2 of 65.
Object-oriented programming (OOP) organizes a program around objects. An object bundles data (variables) with the functions that work on that data. A class describes what its objects hold and do, and you create as many objects from it as you need.
In GDScript every script file is a class. Name it with class_name and declare the variables each object holds:
# car.gd
class_name Car
extends RefCounted
var brand: String = "Generic"
var wheels: int = 4extends RefCounted makes Godot free a Car object by itself once no variable refers to it any more. Use it for every class that holds data and is not a node. A script without an extends line extends RefCounted too.
Call new() on the class to create an object, then reach its variables with a dot:
# main.gd
var my_car := Car.new()
print(my_car.wheels) # 4
print(my_car is Car) # trueThe is operator checks which class an object was created from. Printing the object itself shows only an id such as <RefCounted#-9223372009860233781>, so print its variables instead.
The class is the blueprint and each object is a separate thing built from it: calling Car.new() twice gives you two cars.
Challenge
EasyCreate the class Car in car.gd:
- its class name is
Carand it extendsRefCounted - a
Stringvariablebrandthat starts as"Generic" - an
intvariablewheelsthat starts as4
The supplied code reads how many cars to build and creates each one with Car.new(). It prints the number of cars and their wheels in total. When it built at least one car, it reads a brand for the first car and prints the brands of the first and the last car. For the input 3 and Tesla it prints:
Cars: 3
Wheels: 12
First car: Tesla
Last car: GenericYour code goes in 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())
var garage: Array[Car] = []
for i in count:
garage.append(Car.new())
var total := 0
for car in garage:
total += car.wheels
print("Cars: %d" % garage.size())
print("Wheels: %d" % total)
if count > 0:
garage[0].brand = OS.read_string_from_stdin()
print("First car: %s" % garage[0].brand)
print("Last car: %s" % garage[-1].brand)
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