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

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

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

30条回答
  •  忘掉有多难
    2020-11-21 05:45

    They're often interchangeable, but a method usually refers to a subroutine inside a class, and a function usually refers to a subroutine outside the class. for instance, in Ruby:

    # function
    def putSqr(a)
       puts a ** 2
    end
    
    
    class Math2
       # method
       def putSqr(a)
          puts a ** 2
       end
    end
    
    

    In Java, where everything (except package and import statements) must be inside the class, people almost always refer to them as "methods".

提交回复
热议问题