Monday, February 04, 2008

Classes and objects

In every first lesson of object-oriented programming, the concepts of classes and objects are introduced. Typically,

  • an object represents an entity in real life that has states and behaviours, and
  • a class is a blueprint/template/design of a certain type of similar objects.
While these explanations are good and precise, some, if not many, new learners still cannot get the idea and their difference after reading them and the related examples. As majority of learners have procedural programming background, here I try to illustrate the concepts of classes and objects with comparison to functions in procedural programming.

When writing a function, we are defining what will happen when the function is used (invoked). For example, let's define a function sum:

int sum(int a, int b) { int r; r = a + b; return r; }

This definition does nothing more than allowing the system to look up the method's execution when it is used elsewhere. When this function is invoked

int x = sum(100, 200);
the system uses the definition of sum and executes the code in the definition.

In a similar way, a class is the definition of an object. It defines what will happen when the object is used. While using a function is mostly obvious - invoking it, using an object can be more complex - creating it, accessing its data fields, invoking its methods. Here I write a class Circle (as definition of Circle objects):

class Circle { int radius; // data field Circle(int r) { // constructor radius = r; } double getArea() { // method return radius * radius * 3.1416; } }

When Circle objects are used in some other code, the system will look into the class and execute the proper code in the class. For example, with

Circle c = new Circle(10);
the constructor of class Circle will execute and a Circle object is created. With
c.radius = 9;
the data field radius of the newly created Circle will be changed. With
c.getRadius()
the code inside the method getRadius of the Circle will be executed.