Class Inheritance
Class inheritance is a mechanism where you can derive a class from another class
for a hierarchy of classes that share a set of attributes and methods
To inherit from a class, use the extends
keyword:
# Animal.gd
extends Node2D # Inherits from the Global Node2D class
class_name Animal
# Horse.gd
extends Animal # Inherits from the Global Node2D class
class_name Horse
graph TB;
Animal.gd-->|Horse Inherits from Animal|Horse.gd;
In this case, the Animal class is called a superclass, while the Horse class is called the
subclass.
When a subclass inherits from a superclass, the subclass gets all the functions and class
variables of the superclass.
# Animal.gd
extends Node2D # Inherits from the Global Node2D class
class_name Animal
var health: int = 100
func getHealth() -> int:
return health
# Horse.gd
extends Animal
# Horse class has the health variable and the getHealth() method
class_name Horse
func newlyCreatedFunction() -> void:
print(getHealth()) # 100
# Animal.gd
extends Node2D # Inherits from the Global Node2D class
class_name Animal
var health: int = 100
func getHealth() -> int:
return health
# Horse.gd
extends Animal
# Horse class has the health variable and the getHealth() method
class_name Horse
func newlyCreatedFunction() -> void:
print(getHealth()) # 100
Overriding a Superclass Function
You can override a superclass function by merely writing out the function in the subclass.
# Animal.gd
extends Node2D # Inherits from the Global Node2D class
class_name Animal
func attack() -> void:
print("Animal Attacks")
# Horse.gd
extends Animal
# Horse class has the health variable and the getHealth() method
class_name Horse
func attack() -> void:
print("Horse Attacks") # Override function attack()
Why is using inheritance necessary?
Inheritance allows for cleaner code, and it makes it easier for us to define classes.
Basically, you use inheritance when you want to reuse a class.