Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't static classes have non-static methods and variables?

Why can't static classes have non-static methods and variables when non-static classes can have static methods and variables?

What is the advantage of having static methods and variables in a non static class? Though having a static constructor in a non-static class is understandable.

like image 694
Simsons Avatar asked Oct 16 '11 10:10

Simsons


2 Answers

Static classes can't be instantiated in the first place, so even if you could declare non-static (instance) members, they can never be accessed. Since there really isn't a point allowing it for that reason, the language simply prohibits it.

Bear in mind that static classes are just the classes, while there are two things that are directly related to non-static classes: the classes themselves, and the instances/objects of the classes.

A non-static class can have both static and non-static members so that the static members apply to the class, whereas the non-static members apply to the instances of that class.

like image 85
BoltClock Avatar answered Oct 26 '22 06:10

BoltClock


Static class can't contain non-static members because by definition it can't be instantiated so there's no possibility to use these members.

However, static members in non-static class can be used without having class instance - a bit different scenario, i.e. for utility methods or factory methods.

like image 28
NOtherDev Avatar answered Oct 26 '22 08:10

NOtherDev