/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example6_5.cs illustrates how to use a "has a"
relationship
*/
// declare the Engine class
class Engine
{
// declare the fields
public int cylinders;
public int horsepower;
// define the method
public void Start()
{
System.Console.WriteLine("Engine started");
}
}
// declare the Car class
class Car
{
// declare the fields
public string make;
public Engine engine; // Car has an Engine
// define the method
public void Start()
{
engine.Start();
}
}
public class Example6_5
{
public static void Main()
{
// declare a Car object reference named myCar
System.Console.WriteLine("Creating a Car object");
Car myCar = new Car();
myCar.make = "Toyota";
// Car objects have an Engine object
System.Console.WriteLine("Creating an Engine object");
myCar.engine = new Engine();
myCar.engine.cylinders = 4;
myCar.engine.horsepower = 180;
// display the values for the Car and Engine object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.engine.cylinders = " +
myCar.engine.cylinders);
System.Console.WriteLine("myCar.engine.horsepower = " +
myCar.engine.horsepower);
// call the Car object's Start() method
myCar.Start();
}
}
|