What's the difference between a method and a function?

前端 未结 30 3341
粉色の甜心
粉色の甜心 2020-11-21 05:08

Can someone provide a simple explanation of methods vs. functions in OOP context?

30条回答
  •  爱一瞬间的悲伤
    2020-11-21 05:52

    Methods on a class act on the instance of the class, called the object.

    class Example
    {
       public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".
    
       public void UpdateData() // .. and manipulates it (This is a method by the way)
       {
          data = data + 1;
       }
    
       public void PrintData() // This is also a method
       {
          Console.WriteLine(data);
       }
    }
    
    class Program
    {
       public static void Main()
       {
           Example exampleObject1 = new Example();
           Example exampleObject2 = new Example();
    
           exampleObject1.UpdateData();
           exampleObject1.UpdateData();
    
           exampleObject2.UpdateData();
    
           exampleObject1.PrintData(); // Prints "2"
           exampleObject2.PrintData(); // Prints "1"
       }
    }
    

提交回复
热议问题