函数与方法的区别

来源:这里教程网 时间:2026-02-16 13:49:14 作者:

函数与方法的区别

函数是一段可重用的代码。它可以有可以操作的输入数据(i.e。参数),它也可以通过返回类型返回数据。它是过程式和函数式编程语言的概念。

方法:该方法的工作原理类似于函数i.e。它还可以有输入参数/参数,也可以通过返回类型返回数据,但与函数相比有两个重要区别。

    方法与调用它的对象的实例相关联或相关。方法仅限于对包含该方法的类中的数据进行操作。它是面向对象编程语言的一种概念。

简单地说,如果一个函数是类i.e实例的一部分。(对象)然后它被称为方法,否则它被称为函数。

函数方法
它被独立地称为自己的名字。它被它的对象名调用/引用。
当独立调用时,这意味着数据是显式传递或外部传递的。因为它被称为独立,这意味着数据是隐式传递或内部传递的。

函数在过程式程序设计语言(C)中的实现:

// C program to demonstrate a Function  #include <stdio.h>  // Declaration of functionint func(){   printf("\n FUNCTION"); // statement}  int main(){    func(); // calling of function    return 0;}

面向对象编程语言(JAVA)中函数的实现:

/* a method is similar in working to function but it belongs or is associated with the instance of a class i.e. object */  import java.io.*;  // Declartion of classclass demo {    public int method()    {        System.out.println("METHOD");        return 0;    }}class GFG {    public static void main(String[] args)    {        demo test = new demo();        test.method(); // here you can see method belongs to                     // instance of a class named demo and is                     // called using object(test) of a                     // class(demo), so it is a method    }}

相关推荐