@@ -2002,6 +2002,70 @@ in other scripts without the need to ``load`` or ``preload`` them:
2002
2002
automatically hidden by the editor windows along with the built-in editor nodes used
2003
2003
by the Godot editor.
2004
2004
2005
+ .. _doc_gdscript_basics_abstract_class :
2006
+
2007
+ Registering abstract classes
2008
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2009
+
2010
+ Since Godot 4.5, you can register abstract classes using the ``abstract `` keyword.
2011
+ An abstract class is a class that cannot be instantiated directly. Instead, it
2012
+ is meant to be subclassed by other classes. Attempting to instantiate
2013
+ an abstract class will result in an error.
2014
+
2015
+ For example, you could have an abstract class called ``Shape `` that defines
2016
+ a method called ``draw() ``. You can then create subclasses like ``Circle ``
2017
+ and ``Square `` that implement the ``draw() `` method in their own way.
2018
+ This allows you to define a common *interface * for all shapes without
2019
+ having to implement all the details in the abstract class itself:
2020
+
2021
+ .. code-block :: gdscript
2022
+
2023
+ abstract class Shape:
2024
+ func draw():
2025
+ # It is possible for subclasses to call the parent class method using `super()`.
2026
+ # In this example, we won't use `super()` to call the parent class method,
2027
+ # so we can leave this method empty.
2028
+ pass
2029
+
2030
+ # This is a concrete (non-abstract) subclass of Shape.
2031
+ class Circle extends Shape:
2032
+ func draw():
2033
+ print("Drawing a circle.")
2034
+
2035
+ class Square extends Shape:
2036
+ func draw():
2037
+ print("Drawing a square.")
2038
+
2039
+ Both subclasses and classes created using ``class_name `` can be abstract. This
2040
+ example creates two abstract classes, one of which is a subclass of another
2041
+ abstract class:
2042
+
2043
+ .. code-block :: gdscript
2044
+
2045
+ abstract class_name AbstractClass
2046
+ extends Node
2047
+
2048
+ abstract class AbstractSubClass:
2049
+ func _ready():
2050
+ pass
2051
+
2052
+ # This is an example of a concrete subclass of AbstractSubClass.
2053
+ # This class can be instantiated using `AbstractClass.ConcreteSubclass.new()`
2054
+ # in other scripts, even though it's part of an abstract `class_name` script.
2055
+ class ConcreteClass extends AbstractSubClass:
2056
+ func _ready():
2057
+ print("Concrete class ready.")
2058
+
2059
+ .. warning ::
2060
+
2061
+ Since an abstract class cannot be instantiated, it is not possible to attach
2062
+ an abstract class to a node. If you attempt to do so, the engine will print
2063
+ an error when running the scene:
2064
+
2065
+ ::
2066
+
2067
+ Cannot set object script. Script '<path to script>' should not be abstract.
2068
+
2005
2069
Inheritance
2006
2070
~~~~~~~~~~~
2007
2071
0 commit comments