Inheritance
Like all object-oriented programming languages, Lua++ supports full class inheritance. To inherit all the heritable properties of a class in Lua++, one would separate the class name from the base class using a colon in this way: tag : base-class
, and for multiple class inheritance, one would separate each base class with a comma: tag: base-1, base-2, ...
as shown in the following example:
class Person {
firstName: string,
lastName: string,
constructor(firstName: string, lastName: string)
self.firstName = firstName
self.lastName = lastName
end,
function getName(): string
return self.firstName .. " " .. self.lastName
end,
function getDescription(): string
return "This is " .. self.getName() .. "."
end
}
Here we define a base class Person
, with the firstName
and lastName
properties. This class has two public methods, getName()
, and getDescription()
. As mentioned earlier, to inherit a class you use the :
operator. For example, the following Employee
class inherits properties and methods from the Person
class:
class Employee : Person {
}
Since the Person
class has a constructor that initializes the firstName
and lastName
properties, you need to initialize these properties in the constructor of the Employee
class by calling its parent class’ constructor. This can be done by using the base()
keyword.
class Employee : Person {
job: string,
constructor(firstName: string, lastName: string,
job: string)
self.job = job
-- Call the constructor of the person class
base(firstName, lastName)
end
}
The following creates an instance of the Employee
class which inherits all the methods and properties of the Employee
class:
local employee: Employee = Employee("Max", "Prihodko", "Programmer")
Lua++ also allows you to override methods inherited by a base class. This can be done by using the :
symbol after the name definition of the class.
class Employee : Person {
job: string,
constructor(firstName: string, lastName: string,
job: string)
self.job = job
-- Call the constructor of the person class
base(firstName, lastName)
end,
function describe(): string
return base.describe() .. " I am a " ..
self.job .. "."
end
}
local employee: Employee = Employee("Max", "Prihodko",
"Programmer")
print(employee.describe())
The output of this fragment of code will be:
This is Max Prihodko. I am a Programmer.
Last updated
Was this helpful?