Wednesday, April 9, 2014

Why and when should I make a class 'static'? What is the purpose of 'static' keyword on classes? With real time example

What is a static class?

It is a class which cannot be inherited and its members can be accessed directly without instantiating it.

There are two features of a static class, one is we can not create an instance of static class and second is a static class must contain only static members, Then what is the benefit to create a static class, the benefit of making static class, we do not need to make any instance of this class ,all members can be accessible with its own name.
Is it enough to clear your question? I think No!!
Because the same answer you will get from anywhere and we are still not able to clear what is static class.
Real time answer:
Assume we are working payroll project which provides all the employee details related to salary and leaves etc, Also have an admin who can check the details of all employee. It’s a big project and has lots of modules like:

Ø  Employee Details
Ø  Employee Salary Details
Ø  Employee Attendance Details
Ø  Admin module

In such kind of project apart from having many functions/properties and classes, you may need to have calculator to calculate the  the employee salary, Example- you may need the average salary , To create that calculator class you can use static class that would not be related to any other object of your other modules. We use these classes to invoke the functions with parameters or without parameters and then they return the output only, do not relate to other object of your projects.

Hope this will help.


No comments:

Post a Comment