Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static and non static members? [duplicate]

Tags:

c#

Possible Duplicate:
What’s a static method in c#?

I found it difficult to clear my mind about the actual concept of static and non-static(instance) members, after researching from so many forums i decided to put my question here:

What is the difference between static and non static members?

like image 952
Ammar Raja Avatar asked Oct 31 '12 10:10

Ammar Raja


People also ask

What is the difference between static and non static members?

static members are accessed by their class name which encapsulates them, but non-static members are accessed by object reference. static members can't use non-static methods without instantiating an object, but non-static members can use static members directly.

Can static members have multiple copies?

Yes, if the same class is loaded in different class loaders, then each copy of the class will have its own statics.

What is the difference between a static member of a class and non static member of class?

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.

What is the difference between static and instance members?

So, in summary, an Instance member is a member that belongs to an Instance of an object (in our example, the objects are c1 , c2 , and c3 ) whereas a static member belongs to the class itself and does not require an instance of an object as was demonstrated by making a call to CloneGenerator.


1 Answers

The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed.

In OOP, static variables are used for values which cannot be stored by an instance variable. static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class we are trying to refer.

e.g. Supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

References:

  1. Static vs. Non-Static method in C#
  2. Static vs. non-static method
like image 98
Furqan Safdar Avatar answered Oct 11 '22 11:10

Furqan Safdar