Recently I’ve had the opportunity to work with others on a new game. In that period I noticed sometimes concepts can be lost over time such as Instance vs Static properties. Today, I wanted to provide a brief interpretation of the differences, starting with instance properties.

 

Instance Properties

What are instance properties? One way to put them is properties on an object that can change. They are directly tied to the state of the object. The object? An instance of a class. To illustrate, here’s an example of an instance property in action.

// A class; a template for creating objects with the properties listed in the class
class Duck {
public var age:Int;
public function new(age:Int) {
this.age = age;
}
}
class Test {
static function main() {
var ducky = new Duck(3);
trace(ducky.age);
// Using the instance variable to change the age
ducky.age = 4;
trace(ducky.age);
}
}

view raw
InstanceExample.hx
hosted with ❤ by GitHub

The main idea is that they are changeable properties of an object you create. Make sense? Now, if we bring static into the mix, things change.

 

Static Properties

Static properties are the opposite of instance properties. They are attached to the class itself; they do not / are not modifiable when using the final keyword. How is that different from an instance property? They also don’t exist on an object(Instance of the class). Let’s take a look at both properties in Haxe and see how they differ. Let’s show a class with both properties and how they’re used.

//A class; a template for creating objects with the properties listed in the class
class Duck {
static public var CAN_FLY:Bool = true;
public var age:Int;
public function new(age:Int) {
this.age = age;
}
}
class Test {
static function main() {
var ducky = new Duck(3);
// A static property uses the class name in order to access the element
trace(Duck.CAN_FLY);
// ducky.CAN_FLY = false; //Try uncommenting this line and see what happens
trace(ducky.age);
// Using the instance variable to change the age
ducky.age = 4;
trace(ducky.age);
}
}

As you can see, it makes a difference. Look at how each property is used and set up. Notice how the static property uses the static keyword. Keep this in mind as most languages do this. Try assigning/setting the property to something. Try it at this link here in the Haxe programming language.  Experimentation will solidify the ideas in your head. With that said, I hope this helps, and good luck game-making!!

%d bloggers like this: