Tuesday, March 16, 2010

Static Members and Static Classes

Assume we are building a class that represents a group of employees working for a company. The employee’ names change with each instance of the class, while the company name stays the same. In other words, the employee name belongs to the corresponding employee object, while the company name belongs to the class. In this case we can modify it to belong to the class rather than a specific object.
Here is the new declaration:
private static string companyName = “Microsoft”;
private string name;
when we use a static field, we associate it with the class name rather than a particular object:
Console.WriteLine(“Company Name: {0}”, Employee.CompanyName);
This leads to classifying the class members into two categories:
•    Instance members
•    Static members
This classification applies to methods and fields.
Example: -
//Example 5-7.cs
//Static properties example.
using System;
public class Employee
{
    //Declare the private fields:
    private static string companyName = “T-Mobile”;
    private string name;
   
    // The Name property—read write:
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    //The company name property – read – only:
    public static string CompanyName
    {
        get { return companyName; }
        private set
        {
        comapnyName = value;
        }
    }
}
public class MainClass
{
    public static void Main()
    {
        Employee emp = new Employee();
        Emp.Name = “Sallary Abolrous”;
        Console.WriteLine(“Company Name: {0}”, Employee.CompanyName);
        Console.WriteLine(“Employee name:{0}”,emp.Name);
    }
}
Note: - A static class is a class whose members are all static and is declared using the modifier static. Static classes cannot be instantiated or inherited.

No comments:

Post a Comment