static means something cannot be instantiated in our development. In other words, we cannot create an object of a static class, and we access the static members without instantiating an object of a static class.
static modifier before the class name and after the access modifier (
private) to make a class static. By making a class static, we cannot create an object of the class, and we can access its members without instantiating an object of the class. Therefore, the members of the static class can be accessed using a class name.
Keep one thing in mind, all the members of a static class should be static, otherwise it will trigger a compile error.
- Static class cannot be instantiated and static class cannot contain instance members and constructors
- Static class is sealed, which means the class cannot be inherited
- All members of a static class must be static
Talk Is Cheap, Show Me The Code
As Calculator class is a static class, we don’t need to create an object of the class when we need to access its members. In line 9, we access the
Sum function by calling the class name.
Static Members in Non-Static Class
A variable is can be declared as static in a non-static class. Once a static variable is created, a copy of the variable will be shared among all objects at the class level. We don’t need to create any objects to access its variables.
We can define multiple static methods in non-static classes. Static methods can be called without creating objects of these classes.
Static methods can only call other static methods and access static members; otherwise, calling non-static methods or access non-static members will trigger an error.
A non-static class can contain one static constructor, which is a parameter-less constructor.
The static constructor is called once when the instance is created or static constructor is called in the first time.
- Static Constructor is called once in the lifespan
- Static Constructor can only access static memebers