2. Classes and Objects¶
Learning Objectives
- be familiar with how to create and use classes
- understand the difference between classes and objects
- see the relationship between classes and OOP
Classes¶
Classes can be seen as blueprints for creating objects which are different instances of the same class. Classes allow us to define the common characteristics and behaviours of a group of related objects.
Take for instance, the wrapper classes like String
in Java or std::string
in C++, we have the stored data (the text string) and a bunch of methods which act on that data (e.g. length()
returns the length of that string data). This is an abstraction and encapsulation like we've seen before, except that we can have different instances instead of being confined to a Singleton.
For instance:
-- CarClass.lua
local Car = {}
Car.__index = Car
function Car.new(color, speed)
local self = setmetatable({}, Car)
self.color = color
self.speed = speed
return self
end
function Car:Drive()
print("The " .. self.color .. " car is driving at " .. self.speed .. " mph.")
end
return Car
Here, Car.new
is the constructor that initializes a new object of class Car
and returns it, and Car:Drive
is a method available to all instances of the Car
class.
Objects¶
Objects are the concrete realization of a class. While a class defines the general structure and behaviour, an object represents a specific instance created from that class, with its own unique data.
For instance, we can create Car
objects like this:
local Car = require(game.ServerScriptService.CarClass)
local redCar = Car.new("red", 60)
local blueCar = Car.new("blue", 80)
redCar:Drive() -- Outputs: "The red car is driving at 60 mph."
blueCar:Drive() -- Outputs: "The blue car is driving at 80 mph."
Object-Oriented Programming¶
Object-oriented programming (OOP) is the programming paradigm based upon the concepts of objects in order to model our programming problems.
One way to look at OOP is as a mirror of our natural world, to break everything down into objects which have certain properties, exhibit certain behaviours, and allow certain actions.