How to make a Node override an abstract function?

Godot Version

4.7.2

Question

I have an abstract class that defines behavior which I want many different types of Nodes in my game to share. This class also defines abstract functions, the implementation of which needs to be specific to each Node.

@abstract
class_name GameObject

@abstract
func foo()

func bar():
    pass # Do something.

Problem is, I can’t actually extend this class in any of my scripts, since those scripts must already extend the Node type. The only solution I was able to come up with is using composition and giving the functions a reference to the Node, like this:

@abstract
class_name GameObject

@abstract
func foo(source)

func bar(source):
    pass # Do something. bar() also needs the source to be able to call foo().
class_name MyNode
extends Node

var game_object: MyGameObject

# MyNode's logic.
# At some point calls like this happen:
# game_object.foo(self)
# game_object.bar(self)

class MyGameObject extends GameObject:

func foo(source):
    # Implement, referencing logic specific to MyNode

# Repeat the above for Area, CharacterBody, etc.

This notation is convoluted to say the least and also not really what inner classes are intended for. The solution to this is of course interfaces, but from what I read that’s not gonna happen anytime soon.

Does anyone know a more elegant way to implement this concept?

Let the abstract class inherit Node.

I need this to work on many different node types, like Area, CharacterBody, etc.

Then inheritance is not the tool to use.

GDScript only allows single inheritance, so a shared base class can’t sit above Area, CharacterBody and Node all at once. One pattern that works well here is to turn the shared logic into a small component node: make GameObject extend Node, and add it as a child of whatever Area or CharacterBody needs the behavior. Inside the component you can get the owner with get_parent(), so you no longer have to pass source into every call. For the parts that differ per node type, you can either have the parent expose a method and check it with has_method() before calling it, or let the component emit a signal that the parent connects to and implements. That keeps the shared code in one place and the node-specific code in each script, without the self argument everywhere.

That sounds like a good solution. I think I’ll try out the signal approach.