What is a class?

A class is a template which defines the attributes (as member variables) and behaviours (as member methods) of objects created from that class.

This models the real world. For example, a scooter has two wheels (attributes) and accelerates (behaviour). Check the code below. It is conventional to type member variables at the top of the class then member methods.

public class Scooter
{
    private int Wheels;
    private string Name;
    private string Model;

    public void Accelerate()
    {
        // code to accelerate here
    }
}

Note: ENCAPSULATION

Member variables should be defined as private. This means that they cannot be directly accessed outside of the class. Find out more here.

The constructor method

The constructor is a special method which is automatically called when an object of the class is created. It is normally used to initialise member variables.

There are three rules for a constructor:

  1. It is public.
  2. It has no return type, not even void.
  3. It has the same name as the class.
public Scooter(int w, string n, string m)
{
    Wheels = w;
    Name = n;
    Model = m;
}

Overloading methods

Any method can be overloaded. This means that you can create multiple methods with the exact same name but different parameter variables. In the following example the constructor method has been overloaded to take one parameter variable.

public Scooter(string n)
{
    Name = n;
}

The rules for overloading is that the parameter variables must differ in quantity, data type or both. Thus the following methods would also be acceptable.

public Scooter(int w)
{
    Wheels = W;
}

public Scooter(string N, int W)
{
    Name = N;
    Wheels = W;
}

However since the parameter variable name and method return type are ignored adding the following method to those above would cause a compile error. There is already a constructor method which takes one integer as a parameter variable.

public Scooter(String M)
{
    Model = M;
}

The Scooter class with overloaded constructor methods

Here is the Scooter class with the overloaded constructors.

public class Scooter
{
    private int wheelCount = 2;
    private string name = "";

    public Scooter()
    {
        // initialise member variables here
    }

    public Scooter(string n)
    {
        name = n;
    }

    public Scooter(int w)
    {
        wheelCount = w;
    }

    public Scooter(int w, int n)
    {
        name = n;
        wheelCount = w;
    }

    public void Accelerate()
    {
        // code to accelerate here
    }
}

Note: It is conventional to type any constructor methods before other member methods in the class.