Menu
CoddyTech

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 familiaris

The 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) # Unnamed

Changing 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 icon

Challenge

Easy

Complete the class Student in student.gd:

  • a constant SCHOOL with the value "Godot High School", shared by the whole class
  • a String variable student_name
  • a String variable grade that 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/A

Your 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])
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