Class Definitions


Classes

A class is a template that defines the form of an object. A class can contain data and methods that act on the data. It is important to realise that a class does not represent an object but supplies the definition of all objects of that type.

A class is created using the class keyword. The general form of a generic declaration is as follows.

class class_name
{
 // declare fields

 var1
 var2
 ...
 varn

 // declare methods

 method1(parameters)
 {
  ...
 }

 method2(parameters)
 {
  ...
 }

 ...

 methodn(parameters)
 {
  ...
 }
}

where the ellipsis (...) means that code is inserted.

Defining a Class

A first example of a class will be a 2 dimensional point called point. The generic is shown below. The 'struct' keyword is used to cause a default constructor to be created.

struct point
{
    x
    y
}

Placing this class in a program is demonstrated below.

// point_a - a first example of a generic

struct my_point
{
    x
    y
}

point_a()
{
   p = new my_point()
   p.x = 100
   p.y = 200

   r = new my_point()
   r.x = 300
   r.y = 400

   s = "point = (" + p.x.to_string() + "," + p.y.to_string() + ")"
   s.println()
   s = "point = (" + r.x.to_string() + "," + r.y.to_string() + ")"
   s.println()
}

The output of this program is as follows.

point = (100,200)
point = (300,400)

While this class is simple, it is sufficient to demonstrate some salient points about classes. The template for the class point indicates that it contains two fields called x and y. Note that the class acts as a template, indicating that every object of class point has these same two numbers as the data.

An object of the class point is allocated through the statement

p = new my_point()

Once a point (p) has been allocated, its fields are initialized through the following statements.

p.x = 100
p.y = 200

These statements initialize the x and y fields of the point p using the dot operator. The dot operator links the name of an object with the name of a member. The general form of the dot operator is shown below.

object.member

The object (p or r in this case) is placed on the left and the member name (x or y in this case) is placed on the right. The dot operator can be used to access both fields and methods of a class.

It is worthy to note that each object of class point bares no connection to another object of that class. Thus, in the above program, the points p and r are not connected and each have there own memory - as shown in the figure below.

point p
x 100
y 200
point r
x 300
y 400