Sunday, June 2, 2013

Static class Modifiers.

When a class is defined as a static class its members can be accessed without creating an instance of the class. Static classes are useful when we want to define members which do not vary from one instance to another.

The following example creates a static class with a static variable and a function.
    public static class StaticClass
    {
        private static string strName;
        public static string getName()
        {
            return strName;
        }
    }

Static classes cannot be instantiated i.e we cannot create an object from a static class, trying to do so will result in a compiler error as follows.

Cannot create an instance of the static class StaticClass

The members of a static class should also be defined with the static keyword, failing to do so will result in a compiler error.

The following example tries to create a non static member in a static class and results in error.

Static class without static members
    public static class StaticClass
    {
        string strName;
        public string getName()
        {
            return strName;
        }
    }

Error
StaticClass.strName: cannot declare instance members in a static class
getName: cannot declare instance members in a static class

Search Flipkart Products:
Flipkart.com

No comments: