Classes vs Objects
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 3 of 65.
A class and its objects hold different things. A const in a class belongs to the class itself: there is one value, and you read it through the class name without creating an object.
# dog.gd
class_name Dog
extends RefCounted
const SPECIES = "Canis familiaris"
var dog_name: String = "Unnamed"
var breed: String = "Unknown"print(Dog.SPECIES) # Canis familiarisThe var lines describe what each object holds. Every object created with new() gets its own copy of these variables, starting from their default values:
var dog1 := Dog.new()
var dog2 := Dog.new()
dog1.dog_name = "Nicky"
dog1.breed = "Husky"
print(dog1.dog_name) # Nicky
print(dog2.dog_name) # UnnamedChanging dog1 leaves dog2 as it was. An object can read the constant too: dog1.SPECIES is the same value as Dog.SPECIES.
An object has only the variables its class declares. dog1.color = "brown" stops the program with an error, because Dog has no color variable. Every variable an object needs goes into the class.
Challenge
EasyComplete the class Student in student.gd:
- a constant
SCHOOLwith the value"Godot High School", shared by the whole class - a
Stringvariablestudent_name - a
Stringvariablegradethat starts as"N/A"
The supplied code reads how many students follow, then one line per student: a name, optionally followed by a space and a grade. It creates a Student for each line, sets its name, and sets its grade only when the line has one. Then it prints Student.SCHOOL and every student. For the lines Alice A and Bob it prints:
School: Godot High School
Alice has grade A
Bob has grade N/AYour code goes in student.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 students: Array[Student] = []
for i in count:
var parts := OS.read_string_from_stdin().split(" ", false)
var student := Student.new()
student.student_name = parts[0]
if parts.size() > 1:
student.grade = parts[1]
students.append(student)
print("School: %s" % Student.SCHOOL)
for student in students:
print("%s has grade %s" % [student.student_name, student.grade])
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