A class is a user-defined data type that holds its own data members and member functions that can be accessed and used by creating one or more instances of that class. Every time a class is instantiated, the values that it holds are different and unique to the particular instance or object and not to that class. Static Classes brings forth a property wherein a class itself holds values that remain the same and aren’t unique. Another property of Static Classes is that we can do the aforementioned without having to create an instance of the class.
How to create a static class?
It’s fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first.
An important point to note here is that, since this means a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods since these require an instance of the class.
To access the static class and it’s method use the following synatx:
Example 1: The following code returns the current date without instantiating the class Date. In this case, the format of the date and not the actual date remains the same.
Output: April 30th, 2020 2020/04/30 10:48:36
Example 2: The following code checks whether the string is valid or not. It is valid if it’s length is equal to 13.
String is valid! String is NOT valid!