Abstract variable?

Godot Version

v4.5.1.stable.official [f62fdbde1]

Question

Is it possible to make an ‘abstract variable’ in godot? I’m not sure if I use the term correctly but this is what I’d like to do:

Abstract class:

@abstract
class_name MyAbstractClass

var my_abstract_var : String
extends MyAbstractClass
class_name MyClass

var my_abstract_var : String = "My String Here"

If I do this, I get an error:

The member "my_abstract_var " already exists in parent class MyAbstractClass.

you cant override variables in script by redeclaring them. The only way this work is to either set these values in a method(_ready or _init, for example) or to use @export for scenes

1 Like

No. It is not possible in any language. It is possible to make an unassigned variable. (Which then equals null in GDScript.)

class_name MyBaseClass

var my_undefined_variable: String
class_name MyClass extends MyBaseClass


func _ready() -> void:
	my_undefined_variable = "My String Here"

Alternately:

class_name MyBaseClass

@export var my_undefined_variable: String
class_name MyClass extends MyBaseClass

#Set the variable in the inspector

The @abstract keyword is something you should only be using if you understand object oriented programming and how and when to use abstract classes. The @abstract keyword is often overused even by experienced developers.

An abstract class must have NO implementation of code. That means it does nothing unless it is extended by an inherited class which then must implement all functions. It is useful when you say have a CollisionShape2D Shape (i.e. the Shape that goes inside it), and they all have to implement the same things but their implementations are so very different that it doesn’t make sense for them to share boilerplate code.

Abstraction is not necessary to implement inheritance. And if used incorrectly, it makes code MORE difficult to understand. Abstract classes are something that feel very clever when you implement them (like internal classes), but become very hard to maintain when you come back to them later.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.