Instance and class members

In object-oriented programming, the members (variables or methods) of a class can either be instance members or class members. Instance members are created for each instance of the class; class members are created just once per class.

To understand the difference between instance and class members, consider the Person class example discussed in Using classes: a simple example. It declares two properties (age and name) and a single method (showInfo()).

class Person {
	// Instance properties
	var age:Number;
	var name:String;
	
	// Instance method
	function showInfo() {
		return ("Hello, my name is " + name + " and I'm " + age " years old.");
	}
}

The following code creates two instances of the Person class named person_1 and person_2.

var person_1 = new Person("Nate", 32);
var person_2 = new Person("Kate", 45);

Each Person object, or instance of the Person class, contains a separate copy of all the members defined in the Person class. That is why these members are called instance members. To invoke an instance method, or access an instance property, you reference an instance of the class. For example, the following code invokes the showInfo() method on the person_1 instance.

person_1.showInfo();

In contrast, class members, also known as static members, are assigned to the class itself, not to any instance of the class. To invoke an class method, or access a class property, you reference the class name itself, rather than a specific instance of the class.

For example, all the methods and properties of the ActionScript Math class are static. To call the Math.sqrt() method, you don't need to create an instance of the Math class. You just call the method on the class name itself. The following code uses the Math.sqrt() method to get the square root of four (4).

var value:Number = Math.sqrt(4);

You don't first create an instance of the Math object (var myMath = new Math()), and then call the sqrt() method on that instance (myMath.sqrt(4)). You just call the method, a class method, on the class itself.