Sunday, February 8, 2004

Tutorial 1 - Classes, objects and methods

This post was from my original website, but giving it a new home here.

This will quickly introduce you to classes, objects and methods in C#. It pretty much just jumps right in. If you'd prefer to see a hello world example, go here.

Three important terms in object oriented programming are classes, objects, and methods. Sun defines objects and classes as follows:

  • An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life.
  • A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.

In common terminology, an object is an instance of a class.

A method is basically a function in C++, but unlike C++, they always belong to classes. That is, classes contain methods. Think of methods as the "verbs" of an object/class. They do things.

Airplane Example

Let's take an example of an airplane. We will create a class called Airplane that defines an airplane. We will define an airplane as having a manufacturer, model, altitude, direction and speed. These are all stored in fields. We will also define actions for the airplane like "TakeOff", "Land", "SetCourse" etc. These are all methods for the airplane. While there are many other things that make an airplane, these are the only ones we care about. This is abstraction: taking a complicated thing like an airplane and only dealing with certain parts of interest.

Here's some C# to define an Airplane class, and to create a specific airplane object. In this example, our instance of an airplane is a Boeing 747 traveling at 30,000 feet directly east.

Notes: I am ignoring access modifiers here (public vs. private) and also am not using a great aspect of C# called properties. We'll take a look at those next.

using System;
namespace Tutorial
{
  public class Airplane
  {
      string manufacturer;
      string model;
      int altitude;
      int direction;
      int speed;
      // This function is a constructor. It is used
      // to create a new Airplane instance (or object).
      public Airplane(string manufacturer, string model)
      {
          this.manufacturer = manufacturer;
          this.model = model;
          this.altitude = 0;
          this.direction = 0;
          this.speed = 0;
      }

      // Make the airplane takeoff
      public void TakeOff ()
      {
          this.altitude = 30000;
          this.speed = 500;
      }

      // Make the airplane land
      public void Land ()
      {
          this.altitude = 0;
          this.speed = 0;
      }
      
      // Set a new course for the airplane
      public void SetCourse (int newDirection)
      {
          this.direction = newDirection;
      }
      
      // override is used because all objects
      // have a default ToString() method, we want
      // to override that default method with this
      // new method.
      public override string ToString()
      {
          string message;
          if (altitude == 0)
          {
              message = this.manufacturer + " " + this.model +
              " is currently on the ground.";
          }
          else
          {
              message = this.manufacturer + " " + this.model +
              " flying " + this.speed + " mph" +
              " with bearing " + this.direction +
              " at an altitude of " + this.altitude + " ft.";
          }
          return message;
      }

      public static void Main ()
      {
          // Create an airplane.
          Airplane airplane1 = new Airplane ("Boeing", "747");
          // Make it take off
          airplane1.TakeOff();
          // Set a course 90 degrees (east)
          airplane1.SetCourse (90);
          // Display information about the airplane
          Console.WriteLine(airplane1.ToString());
          Console.ReadLine();
      }
  } // End of class
} // End of namespace

Examining the program

Let's look at some major parts of the above program.

Namespaces

The first few lines deal with namespaces.

using System;
namespace AirplaneTutorial
{ . . . }

Namespaces provide scope and group classes together by function (web, database, windows forms, etc.) System is a broad namespace that contains many other sub-namespaces. It also contains classes such as Console, which is used for reading and writing to the console. The full name for the function to write to the console is:

System.Console.WriteLine("Write to screen");

The directive using indicates that we are using classes from the System namespace and allows us to shorten the method call to just:

Console.WriteLine("Write to screen");

The keyword namespace creates a new namespace called "Tutorial" for our class. Other people wanting to use our class would reference it as Tutorial.Airplane. Or they could use the statement: using Tutorial; and then reference our Airplane directly.

Classes

Next we declare our Airplane class. All of the code between the braces belongs to the class Airplane. The code describes what an airplane is, how to create one, and how to use one.

public class Airplane
{ . . . }

As described earlier, our class contains fields to store information about an airplane and methods to make an airplane do things. There is also a special method called Main. This is where the program begins running.

As it runs

Let's analyze what happens as the program runs. The program begins running in the Main function.

public static void Main ()
{

The first line of Main creates a new airplane.

// Create an airplane.
Airplane airplane1 = new Airplane ("Boeing", "747");

The first two words (Airplane airplane1) define a variable, airplane1, which will hold a reference to an Airplane object. Objects like Airplane are stored on the heap, which is an area of memory in the computer. We need a way to access objects, and variables give us a way to do that. A good analogy is this:

Objects are like balloons. References are strings to balloons. And variables are like your hand. You hold a reference, which is connected to an object (balloon). The line of code above is creating a new balloon (an Airplane object), and giving your hand (the variable airplane1) a string (reference) to it.

The keyword "new" followed by a class name "Airplane" means we are creating a new Airplane object. This means a specific area of memory has now been reserved on the heap for one instance of an airplane. Next we need to create the airplane. This is the job of constructors.

A constructor is a special method used to create new objects. It is a method that has the same name as the class. This is our Airplane constructor, which requires a manufacturer and model.

// This function is a constructor. It is used
// to create a new Airplane instance (or object).
public Airplane(string manufacturer, string model)
{
  this.manufacturer = manufacturer;
  this.model = model;
  this.altitude = 0;
  this.direction = 0;
  this.speed = 0;
}

When the function is called, it is passed strings representing the manufacturer and model. Memory on the heap has already been reserved for the new airplane instance, but we need to initialize it here. The keyword "this" means that we are updating variables for this (new) instance of an airplane. (Note: the value for altitude, direction, and speed would all default to 0 since that is the default value of an int. Setting them to 0 in the constructor accomplishes nothing.)

Next, we run methods on our airplane instance. We make it takeoff and set a new

course. These run the methods (functions) described by the Airplane class. TakeOff will set our altitude and speed, while setCourse will change our direction of travel.

// Make it take off
airplane1.TakeOff();
// Set a course 90 degrees (east)
airplane1.SetCourse (90);

Finally, we can see information about the airplane by calling a method ToString().

// Display information about the airplane
Console.WriteLine(airplane1.ToString());
Console.ReadLine();

Running the program

To run the above program, select and copy it to the clipboard.

To open it in Visual Studio .NET, create a new console application project (File | New Project | C# Console Application). Give it a name. Then open class1.cs, delete the contents of the file and paste the above code into the file. Hit F5 to run it.

From the command line, make sure csc.exe (the C# compiler) is in your path. Typically something like:
C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705 - for version 1.0 of .NET framework.
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 - for version 1.1 of .NET framework.

Copy and paste the above program into a text editor and save as airplane1.cs

> csc airplane1.cs

The resulting airplane1.exe is the compiled program. Run it and it should print out the following line and then wait for you to hit "Enter" before exiting.

> airplane1.exe
Boeing 747 flying 500 mph with bearing 90 at an altitude of 30000 ft.

That's a pretty simple, but complete, C# program.

No comments: