类继承

类继承是一种机制,您可以在其中从另一个类派生一个类,以获得共享一组属性和方法的类层次结构
要从类继承,请使用extends关键字:

  1. # Animal.gd
  2. extends Node2D # Inherits from the Global Node2D class
  3. class_name Animal
  1. # Horse.gd
  2. extends Animal # Inherits from the Global Node2D class
  3. class_name Horse

在这种情况下,Animal 类称为超类,而 Horse 类称为子类。
当子类从超类继承时,子类获取超类的所有函数和类变量。

  1. # Animal.gd
  2. extends Node2D # Inherits from the Global Node2D class
  3. class_name Animal
  4. var health: int = 100
  5. func getHealth() -> int:
  6. return health
  1. # Horse.gd
  2. extends Animal
  3. # Horse class has the health variable and the getHealth() method
  4. class_name Horse
  5. func newlyCreatedFunction() -> void:
  6. print(getHealth()) # 100
  1. # Animal.gd
  2. extends Node2D # Inherits from the Global Node2D class
  3. class_name Animal
  4. var health: int = 100
  5. func getHealth() -> int:
  6. return health
  1. # Horse.gd
  2. extends Animal
  3. # Horse class has the health variable and the getHealth() method
  4. class_name Horse
  5. func newlyCreatedFunction() -> void:
  6. print(getHealth()) # 100

重写超类函数

您可以通过仅在子类中写出函数来覆盖超类函数。

  1. # Animal.gd
  2. extends Node2D # Inherits from the Global Node2D class
  3. class_name Animal
  4. func attack() -> void:
  5. print("Animal Attacks")
  1. # Horse.gd
  2. extends Animal
  3. # Horse class has the health variable and the getHealth() method
  4. class_name Horse
  5. func attack() -> void:
  6. print("Horse Attacks") # Override function attack()

为什么需要使用继承?

继承允许更简洁的代码,它使我们更容易定义类。
基本上,当你想重用一个类时,你会使用继承。