Illustrates the use of various access modifiers
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example5_10.cs illustrates the use of various
access modifiers
*/
// declare the Car class
class Car
{
// declare the fields
public string make;
protected internal string model;
internal string color;
protected int horsepower = 150;
private int yearBuilt;
// define the methods
public void SetYearBuilt(int yearBuilt)
{
this.yearBuilt = yearBuilt;
}
public int GetYearBuilt()
{
return yearBuilt;
}
public void Start()
{
System.Console.WriteLine("Starting car ...");
TurnStarterMotor();
System.Console.WriteLine("Car started");
}
private void TurnStarterMotor()
{
System.Console.WriteLine("Turning starter motor ...");
}
}
public class Example5_10
{
public static void Main()
{
// create a Car object
Car myCar = new Car();
// assign values to the Car object fields
myCar.make = "Toyota";
myCar.model = "MR2";
myCar.color = "black";
// myCar.horsepower = 200; // protected field not accessible
// myCar.yearBuilt = 1995; // private field not accessible
// call the SetYearBuilt() method to set the private yearBuilt field
myCar.SetYearBuilt(1995);
// display the values for the Car object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
System.Console.WriteLine("myCar.color = " + myCar.color);
// call the GetYearBuilt() method to get the private yearBuilt field
System.Console.WriteLine("myCar.GetYearBuilt() = " + myCar.GetYearBuilt());
// call the Start() method
myCar.Start();
// myCar.TurnStarterMotor(); // private method not accessible
}
}
Related examples in the same category