类继承
类继承是一种机制,您可以在其中从另一个类派生一个类,以获得共享一组属性和方法的类层次结构
要从类继承,请使用extends关键字:
# 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
在这种情况下,Animal 类称为超类,而 Horse 类称为子类。
当子类从超类继承时,子类获取超类的所有函数和类变量。
# 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
重写超类函数
您可以通过仅在子类中写出函数来覆盖超类函数。
# 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()
为什么需要使用继承?
继承允许更简洁的代码,它使我们更容易定义类。
基本上,当你想重用一个类时,你会使用继承。