Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are static classes used?

I have doubts on static class and static methods. From MSDN I understood that "Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class."

So if we don't want to associate a class over an instance , we will make it as static. Is that the only advantage? Can anyone guide me in which real time scenario we go for static class.

Some time in classes(not static) I am finding static methods. What advantage/perfomance advantage do static methods give over instance methods in practical.

like image 371
nehakapoor2010 Avatar asked Feb 09 '10 08:02

nehakapoor2010


People also ask

Why do we use static class in Java?

In Java, the static keyword is primarily used for memory management. We can use the static keyword with variables, methods, blocks, and classes. Using the static class is a way of grouping classes together. It is also used to access the primitive member of the enclosing class through the object reference.

Why do we use static in OOP?

Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to. Static functions can provide functionality related to an a particular class without requiring the programmer to first create an instance of that class.


2 Answers

For utility classes they are great. As you mentioned, they are similiar to global state. So for classes which have no state, for performance benefits the class should be static.

On the other hand, static classes are hard to test (if they contain state). Polymorphism and other OO concepts are also lost.

Use wisely.

like image 59
Finglas Avatar answered Oct 05 '22 00:10

Finglas


Applying the static keyword to a class is a C# language convention, it doesn't mean anything special to the CLR. It merely makes sure that all members are static as well and that you can't accidentally create an instance of the class with the new keyword.

The merits of static methods are discussed in this thread.

like image 35
Hans Passant Avatar answered Oct 04 '22 23:10

Hans Passant