Menu
CoddyTech

Instance Methods

Lesson 24 of 48 in Coddy's GDScript for Java Developers course.

Java instance methods receive an implicit this reference; GDScript similarly supplies self without a declared receiver parameter. A bound Java method reference retains the selected receiver. Methods can mutate instance fields, and repeated calls operate on the same instance. Aliases observe shared mutations. Static methods have no instance receiver. The example toggles a door flag rather than implementing the task numeric accumulator and its independent-instance behavior.

Complete Java comparison. Compile all listed .java files together with Java 17, then run Main.

Java file Door.java:

public class Door { public boolean open=false; public void toggle() { open=!open; } }

Java file Main.java:

public class Main { public static void main(String[] args) { Door d=new Door(); d.toggle(); System.out.println(d.open); } }

Java output:

true

GDScript example file demo_door.gd:

class_name DemoDoor
extends RefCounted
var open: bool = false
func toggle() -> void:
	open = not open

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var door: DemoDoor = DemoDoor.new()
	door.toggle()
	print(door.open)

GDScript output:

true
challenge icon

Challenge

Easy

Implement RunningTotal with value initially zero, add(amount:int)->void and read()->int. Solve adds each input integer. Separate instances stay independent.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in running_total.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var a: RunningTotal = RunningTotal.new()
	var b: RunningTotal = RunningTotal.new()
	a.add(5)
	a.add(-2)
	if a.read() != 3 or b.read() != 0: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Java Developers

Practice on your own: Online GDScript compiler