Saturday 19 January 2013

Difference Between Static And Non Static Method

I will use a slightly different example.  Consider

public class Dog {
   public string Name; // An instance field
   private int weight; // A private instance field
   public static int Population; // A static field
   private static int totalWeight;  // A private static field


   public Dog(string name) {
      Name = name;   // Set the name of this particular Dog
      weight = 500;  // Dogs weight 500g when they are born


      Population++;  // We have one more Animal
      totalWeight += 500;  // The total weight of all Dogs increases by 500g
   }


   public void FeedMe(int foodWeight) {  // An instance method
                                         // because you feed a particular animal
      weight += foodWeight;  // When you feed a particular Dog it gets heavier
      totalWeight += foodWeight;  // The total weight of all Dogs increases
   }


   public static int AverageWeight() {
      return totalWeight / Population;
   }


   public int CurrentWeight() {  // An instance method
      return weight;
   }
}
 You can create and feed a Dog with

Dog MyPet = new Dog("Rover");
MyPet.Feed(200);
Console.WriteLine(MyPet.CurrentWeight); // Prints 700
MyPet.Feed(400);
Console.WriteLine(MyPet.CurrentWeight); // Prints 1100
 and also

Dog yourPet = new Dog("Fido");
yourPet.Feed(400);
Console.WriteLine(yourPet.CurrentWeight); // 900
 What is the average weight of all Dogs?

Console.WriteLine(Dog.AverageWeight); // Prints 1000

No particular Dog knows the average weight of all Dogs.  The method AverageWeight() only uses static fields of the class Dog.  You could declare AverageWeight without static but then you would have to say

Console.WriteLine(MyPet.AverageWeight);  // Prints 1000, YourPet.AverageWeight would give the same answer.

But this would be confusing because the method does not compute the average weight of a particular Dog but rather of all Dogs.

You might like to download and read this fantastic, free book written by the man (Charles Petzold) which, in my opinion, is a great introduction to C#.


PS - My Dog population never goes down and no Dog ever loses weight.  It is an exercise for the reader to handle death, exercise and diets.  Also, in a real application you would need to consider thread safety.

PPS - I realise English is not your first language but using real words rather than SMS speak is a lot friendlier for old people, like me.


No comments:

Post a Comment

If any doubt?then please comment in my post

How to reduce angular CLI build time

 Index: ----- I am using angular cli - 7 and I am going to tell how to reduce the build time as per my knowledge. Problem: -------- Now the ...