Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the static modifier in object-oriented programming?

In one of my interviews, I was asked what the static modifier signifies. I replied by telling the interviewer that static class's object cannot be created and other useful points.

But the interviewer asked what is the use of creating such a class whose objects cannot be created. Basically, they were asking why is static needed in the first place?

I'm not really sure how to answer that question. What should I have said?

like image 471
xorpower Avatar asked Apr 27 '11 11:04

xorpower


2 Answers

The interviewer probably wanted you to discuss object-oriented design and patterns, more so than they wanted you to recite the definition of that particular modifier. There's really no right answer here. Purists might argue that static is an abomination. Pragmatists might argue that it fills a gaping hole in the "everything is an object" abstraction, allowing you to call utility methods for which it doesn't make sense to instantiate a new object just to call them. The canonical example of this is the System.Math class.

The general rule of thumb that most programmers follow is that if the data you're operating on is not associated with any particular instance of an object, it probably makes sense for that field/method to be marked as static. Otherwise, it should probably be a regular member of the object instance.

The MSDN documentation has a pretty good explanation already:

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For more information, see Static Classes and Static Class Members (C# Programming Guide).

The static modifier also has more specific uses in C#, such as defining extension methods (which can only be defined inside of a static class), defining interop methods, etc. It's also worth noting that all static classes are sealed in C#, because without a constructor, they cannot be inherited from.

like image 152
Cody Gray Avatar answered Oct 07 '22 05:10

Cody Gray


Static doesn't just apply to classes, members can be static too. The reason for using static is for providing utility type functionality that doesn't make sense to instantiate an object to use it. E.g. Why would you want to create an int in order to use int.Parse()

like image 3
Ben Robinson Avatar answered Oct 07 '22 05:10

Ben Robinson