skip to main
|
skip to sidebar
static classes and static members
- The static methods can access only static data.
- The static methods are directly access with the help of class name.
- Whenever a class contains all static methods, then the class can be declared static.
- The static classes are not insatiable (it is not possible to create instances of a static class using the new keyword). So, the static classes and class members are used to create data and functions that can be accessed without creating an instance of the class.
- Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object.
- Static classes can be used when there is no data or behavior in the class that depends on object identity.
- Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
- The main features of a static class are:
- They only contain static members.
- They cannot be instantiated.
- They are sealed.
- They cannot contain Instance Constructors.
- Creating a static class is much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
public static class Rectangle
{
public static int CalculateArea(int width, int height)
{
return width * height;
}
}
Note:
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Restrictions on static methods
- this keyword can't be used in static methods.
- The static methods can call only static methods.
- The static methods can access static data directly.
0 comments :
Post a Comment