1. Technology

C# Tutorial - An Object Oriented Approach to Programming


2 of 10

Creating the Classes for the Car Simulation
This is simpler but it comes into its own when we want to modify the road class or even the car class. If we have a truck class which is derived from a car class and has a lower top speed, we can use inheritance to accomplish this by making Travel() and IncreaseSpeed() methods virtual in the Car class and then overriding. We only have to modify the methods in the truck class.

Don't panic if you don't understand these now. The rest of this lesson will show you the code in C# and we'll cover inheritance in the next tutorial.

Objects and Classes

A class is a type; it defines a type of variable just as int and floats are types of numeric variables. To use the class, you have to create an instance of it. This allocates a block of memory to hold the object and returns a reference to this memory address in whichever object variable we have created. For instance
 private Car car= new Car() ; 
This declares a private instance of the class Car in the variable car. As soon as execution reaches this point in the code the following happens.
  • An instance of class Car is created
  • The constructor for class Car is called. Constructors are explained later on in this tutorial.
  • A reference to this instance is stored in the variable car.
At this point you can access any of Car's public methods and properties by calling them via car as in
 car.Travel() ;
 Console.WriteLine("The speed of the car is {0}",car.Speed ) ;

About the Simulation

The rest of this lesson is about a console car simulation using the three classes mentioned. This is about 150 lines of source code which you can download in one zip file containing a Visual C# 2005 Express Edition Solution files. The source code in the file Program.cscan be used with other C# Compilers.

On the Next Page : Coding up the Classes

Related Video
Creating Webpage Frames

©2014 About.com. All rights reserved.