class Employee { public Employee(string firstName, string lastName, int age, double payRate) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.payRate = payRate; } protected string firstName; protected string lastName; protected int age; protected double payRate; public double CalculatePay(int hoursWorked) { // Calculate pay here. return (payRate * (double)hoursWorked); } }
To instantiate this class and use it, we have to declare an instance of it in a method similar to this: -
public static void Main() { Employee emp = new Employee ("Amy", "Anderson", 28, 100); }
In this example, emp is declared as type Employee and is instantiated using the new operator. The variable emp represents an instance of the Employee class and is considered an Employee object. After instantiation, we can communicate with this object through its public members. For example, we can call the emp object's CalculatePay method. We can't do this if we don't have an actual object. (There is one exception to this, and that's when we're dealing with static members. I'll discuss static members in both Chapter 5 and Chapter 6, "Methods.") -
Have a look at the following C# code: -
public static void Main() { Employee emp = new Employee(); Employee emp2 = new Employee(); }
Here we have two instances-emp and emp2-of the same Employee class. While programmatically each object has the same capabilities, each instance will contain its own instance data and can be treated separately. By the same token, we can create an entire array or collection of these Employee objects. Chapter 7, "Properties, Arrays, and Indexers," will cover arrays in detail. However, the point I want to make here is that most object-oriented languages support the ability to define an array of objects. This, in turn, gives you the ability to easily group objects and iterate through them by calling methods of the object array or by subscripting the array. Compare this to the work you'd have to do with a linked list, in which case you'd need to manually link each item in the list to the item that comes before and after it.