Static Classes
A static class can be created using a keyword called "static" used at the class definition. A static class can contain only static members (static data members and static methods). You can‘t create an object for the static class.
Advantages
- If you declare any non-static member, it generates a compile time error, so that it is guaranteed that the class contains only static members; there is no chance of declaring a non-static member accidentally.
- When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name.
Syntax
static class classname
{
//static data members
//static methods
}
Static Members
Types of class members:
- Non-static members: This is the default type for all the members. If you do not use the "static" keyword for the declaration of a field / property or a method, then it can be called a "Non-static member". The main feature of a non-static member is it will be bound with the object only.
Non-static Fields / Properties: The memory is allocated when the object is created.
Non-static Methods: These methods can implement operations on non-static fields and properties.
-
Static Members: If you use the "static" keyword for the declaration of a field / property or a method, then it is called a "Static member". The main feature of a non-static member is that it will not be bound with any object. It is individually accessible with the class name. In other words, the static members are accessible directly, without even creating one object also.
Static Fields / Properties: The memory will be allocated individually, without any relation with the object.
Static Methods: These methods can implement operations on static fields and properties only; and can‘t access the non-static members.
Static Constructors
The static constructor is used to initialize the static data members, whereas the normal constructor (non-static constructor) is used to initialize the non-static data members.
Syntax
static classname()
{
//some code
}
Rules
- Static constructors can‘t contain any access modifiers.
- Static constructors can‘t be defined with arguments.
- Static constructors can‘t access the non-static data members.