X-mas Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Difference between function and method

Difference between function and method

15 Oct 2024
Intermediate
15.2K Views
37 min read
Learn with an interactive course and practical hands-on labs

Java Programming Course

Difference between function and method

Functions and methods are basic concepts in programming. People often use these terms interchangeably, but they have different roles and features. While both are blocks of code designed to perform tasks, a function is independent and can be called without an object, whereas a method is associated with an object or class, often manipulating the object's state. Understanding this difference helps in structuring code in a modular and reusable way.

In this OOPs tutorial, I’ll explain the difference between functions and methods, how they contribute to programming patterns, and why mastering them is key to writing organized and efficient applications.

What Is a Function?

Key Characteristics of a Function:

  • Independent Code Block: Functions are usually independent of any specific object or class. They stand alone and are not tied to any particular data.
  • Reusable: You can use the same function multiple times in your code by calling it whenever needed. This saves time and reduces redundancy.
  • Takes Inputs and Returns Output: Functions can take input parameters (arguments) and often return a result. For example, a function can take two numbers as input and return their sum.
  • Defined Outside of Classes: In most programming languages, functions are defined outside of classes (unless the language is object-oriented, like Java or C#).

Example


using System; // Importing the System namespace

// Calculator class
class Calculator {
    // Method to add two integers
    public int Add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
}

// Main program class
class Program {
    static void Main(string[] args) {
        Calculator calc = new Calculator(); // Create an instance of Calculator
        int result = calc.Add(3, 5); // Call the Add method with 3 and 5
        Console.WriteLine(result); // Output the result: 8
    }
}
            

// Calculator class
class Calculator {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator(); // Create an instance of Calculator
        int result = calc.add(3, 5); // Call the add method with 3 and 5
        System.out.println(result); // Output the result: 8
    }
}
            

# Calculator class
class Calculator:
    # Method to add two integers
    def add(self, a, b):
        return a + b  # Return the sum of a and b

# Main function
if __name__ == "__main__":
    calc = Calculator()  # Create an instance of Calculator
    result = calc.add(3, 5)  # Call the add method with 3 and 5
    print(result)  # Output the result: 8
            

#include <iostream>
using namespace std;

// Calculator class
class Calculator {
public:
    // Method to add two integers
    int add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
};

// Main function
int main() {
    Calculator calc; // Create an instance of Calculator
    int result = calc.add(3, 5); // Call the add method with 3 and 5
    cout << result << endl; // Output the result: 8
    return 0;
}
            

// Calculator class
class Calculator {
    // Method to add two integers
    add(a, b) {
        return a + b; // Return the sum of a and b
    }
}

// Main program
const calc = new Calculator(); // Create an instance of Calculator
const result = calc.add(3, 5); // Call the add method with 3 and 5
console.log(result); // Output the result: 8
            

Output1

8

Explanation

  • In this code, you have a function that adds two numbers together.
  • When you run the program, it calls this function with the numbers 3 and 5, and it gives you the result, which is 8.
  • It is like using a tool to quickly find out how much two numbers add up.

What Is a Method?

Key Characteristics of a Method:

  • Belongs to a Class or Object: A method is always associated with a class or object. You call a method on an instance (object) of a class.
  • Can Access Objects Attributes: Since methods are part of a class, they can access and modify the data (attributes) stored within an object.
  • Requires an Instance to Be Called: Most methods are called on instances of the class they belong to. Some methods, known as static methods, can be called directly on the class without needing an object.
  • Encapsulation: Methods help encapsulate behavior, keeping data and functionality together within an object.

Example


using System; // Importing the System namespace

// Calculator class
class Calculator {
    // Method to add two integers
    public int Add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
}

// Main program class
class Program {
    static void Main(string[] args) {
        Calculator calc = new Calculator(); // Create an instance of Calculator
        int result = calc.Add(3, 5); // Call the Add method with 3 and 5
        Console.WriteLine(result); // Output the result: 8
    }
}
            

// Calculator class
class Calculator {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator(); // Create an instance of Calculator
        int result = calc.add(3, 5); // Call the add method with 3 and 5
        System.out.println(result); // Output the result: 8
    }
}
            

# Calculator class
class Calculator:
    # Method to add two integers
    def add(self, a, b):
        return a + b  # Return the sum of a and b

# Main function
if __name__ == "__main__":
    calc = Calculator()  # Create an instance of Calculator
    result = calc.add(3, 5)  # Call the add method with 3 and 5
    print(result)  # Output the result: 8
            

#include <iostream>
using namespace std;

// Calculator class
class Calculator {
public:
    // Method to add two integers
    int add(int a, int b) {
        return a + b; // Return the sum of a and b
    }
};

// Main function
int main() {
    Calculator calc; // Create an instance of Calculator
    int result = calc.add(3, 5); // Call the add method with 3 and 5
    cout << result << endl; // Output the result: 8
    return 0;
}
            

// Calculator class
class Calculator {
    // Method to add two integers
    add(a, b) {
        return a + b; // Return the sum of a and b
    }
}

// Main program
const calc = new Calculator(); // Create an instance of Calculator
const result = calc.add(3, 5); // Call the add method with 3 and 5
console.log(result); // Output the result: 8
            

Output


8
    

Explanation

  • In this code, you have a class called Calculator that has a method to add two numbers.
  • When you run the program, it creates an instance of the Calculator, calls the method with the numbers 3 and 5, and gives you the result, which is 8.
  • It is like having a special machine that can do an addition for you whenever you need it.

Key Differences Between Functions and Methods

AspectFunctionMethod
AssociationStandalone, not tied to any object or class.Tied to a class or object.
AccessDoes not access object attributes.Can access and modify object attributes.
CallingCalled directly using its name.Called using an object or class instance.
Use CaseGeneral-purpose tasks or calculations.Actions related to a specific object.
DefinitionDefined outside of classes (usually).Defined inside a class.

When to Use a Function vs. a Method

Use a Function When:

  • The code is independent and not tied to any specific data or object.
  • You need a general-purpose tool that you can reuse anywhere in your code.
  • The task does not require access to any object’s state or attributes.

Example:

  • Mathematical operations like addition, subtraction, or utility tasks like formatting a string.

Use a Method When:

  • The code is directly related to a class or object.
  • You need to access or modify an object’s attributes or state.
  • You want to encapsulate behavior within a class to keep your code organized.

Example:

  • Updating the balance of a bank account object, moving a character in a game, or manipulating the properties of a graphical object.

Combined Examples of Methods and Functions

Now, we will use methods and functions within the same example so you will get a clear understanding.
    
    #include <iostream> // Include iostream for input/output
    #include <string>   // Include string for string handling
    
    using namespace std;
    
    // Function to greet
    string greet_function(string name) {
        return "Hello from the function, " + name + "!";
    }
    
    // Greeter class
    class Greeter {
    public:
        // Method to greet
        string greet_method(string name) {
            return "Hello from the method, " + name + "!";
        }
    };
    
    int main() {
        // Using the function to greet
        cout << greet_function("Alice") << endl;
    
        // Creating an instance of the Greeter class
        Greeter greeter_instance;
    
        // Using the method to greet
        cout << greeter_instance.greet_method("Alice") << endl;
    
        return 0;
    }
                
    
    // Function to greet
    string GreetFunction(string name) {
        return "Hello from the function, " + name + "!";
    }
    
    // Greeter class
    class Greeter {
        // Method to greet
        public string GreetMethod(string name) {
            return "Hello from the method, " + name + "!";
        }
    }
    
    // Main program class
    class Program {
        static void Main(string[] args) {
            // Using the function to greet
            Console.WriteLine(GreetFunction("Alice"));
    
            // Creating an instance of the Greeter class
            Greeter greeterInstance = new Greeter();
    
            // Using the method to greet
            Console.WriteLine(greeterInstance.GreetMethod("Alice"));
        }
    }
                
    
    // Function to greet
    public class Greeter {
        public String greetMethod(String name) {
            return "Hello from the method, " + name + "!";
        }
    
        // Static method to greet
        public static String greetFunction(String name) {
            return "Hello from the function, " + name + "!";
        }
    
        public static void main(String[] args) {
            // Using the function to greet
            System.out.println(greetFunction("Alice"));
    
            // Creating an instance of the Greeter class
            Greeter greeterInstance = new Greeter();
    
            // Using the method to greet
            System.out.println(greeterInstance.greetMethod("Alice"));
        }
    }
                
    
    # Function to greet
    def greet_function(name):
        return f"Hello from the function, {name}!"
    
    # Greeter class
    class Greeter:
        # Method to greet
        def greet_method(self, name):
            return f"Hello from the method, {name}!"
    
    # Main code
    if __name__ == "__main__":
        # Using the function to greet
        print(greet_function("Alice"))
    
        # Creating an instance of the Greeter class
        greeter_instance = Greeter()
    
        # Using the method to greet
        print(greeter_instance.greet_method("Alice"))
                
    
    // Function to greet
    function greetFunction(name) {
        return `Hello from the function, ${name}!`;
    }
    
    // Greeter class
    class Greeter {
        // Method to greet
        greetMethod(name) {
            return `Hello from the method, ${name}!`;
        }
    }
    
    // Main code
    const greeterInstance = new Greeter(); // Creating an instance of the Greeter class
    
    console.log(greetFunction("Alice")); // Using the function to greet
    console.log(greeterInstance.greetMethod("Alice")); // Using the method to greet
                

    Output4

    
    Hello from the function, Alice!
    Hello from the method, Alice!
        

    Explanation

    • In this code, you have a function called greet_function that takes a name as input and returns a greeting message.
    • Additionally, there's a class named Greeter with a method called greet_method that does the same thing.
    • When you run the program, it first calls the function to greet "Alice" and then uses an instance of the Greeter class to call the method, which also greets "Alice."
    • It's like having two different ways to say hello!

    Real-world Applications of Functions and Methods

    Functions

    • Mathematical calculations (e.g., trigonometric functions).
    • Utility operations like string manipulations or data formatting.
    • General algorithms, such as sorting or searching arrays.

    Methods

    • Updating the state of a user profile object in a web application.
    • Controlling the movement of a character in a game.
    • Managing the behavior of buttons or UI components in a software application.

    Static Methods: A Special Case

    Example

    
    #include <iostream> // Include iostream for input/output
    #include <string>   // Include string for string handling
    
    using namespace std;
    
    // Function to greet
    string greet_function(string name) {
        return "Hello from the function, " + name + "!";
    }
    
    // Greeter class
    class Greeter {
    public:
        // Method to greet
        string greet_method(string name) {
            return "Hello from the method, " + name + "!";
        }
    };
    
    int main() {
        // Using the function to greet
        cout << greet_function("Alice") << endl;
    
        // Creating an instance of the Greeter class
        Greeter greeter_instance;
    
        // Using the method to greet
        cout << greeter_instance.greet_method("Alice") << endl;
    
        return 0;
    }
                
    
    // Function to greet
    string GreetFunction(string name) {
        return "Hello from the function, " + name + "!";
    }
    
    // Greeter class
    class Greeter {
        // Method to greet
        public string GreetMethod(string name) {
            return "Hello from the method, " + name + "!";
        }
    }
    
    // Main program class
    class Program {
        static void Main(string[] args) {
            // Using the function to greet
            Console.WriteLine(GreetFunction("Alice"));
    
            // Creating an instance of the Greeter class
            Greeter greeterInstance = new Greeter();
    
            // Using the method to greet
            Console.WriteLine(greeterInstance.GreetMethod("Alice"));
        }
    }
                
    
    // Function to greet
    public class Greeter {
        public String greetMethod(String name) {
            return "Hello from the method, " + name + "!";
        }
    
        // Static method to greet
        public static String greetFunction(String name) {
            return "Hello from the function, " + name + "!";
        }
    
        public static void main(String[] args) {
            // Using the function to greet
            System.out.println(greetFunction("Alice"));
    
            // Creating an instance of the Greeter class
            Greeter greeterInstance = new Greeter();
    
            // Using the method to greet
            System.out.println(greeterInstance.greetMethod("Alice"));
        }
    }
                
    
    # Function to greet
    def greet_function(name):
        return f"Hello from the function, {name}!"
    
    # Greeter class
    class Greeter:
        # Method to greet
        def greet_method(self, name):
            return f"Hello from the method, {name}!"
    
    # Main code
    if __name__ == "__main__":
        # Using the function to greet
        print(greet_function("Alice"))
    
        # Creating an instance of the Greeter class
        greeter_instance = Greeter()
    
        # Using the method to greet
        print(greeter_instance.greet_method("Alice"))
                
    
    // Function to greet
    function greetFunction(name) {
        return `Hello from the function, ${name}!`;
    }
    
    // Greeter class
    class Greeter {
        // Method to greet
        greetMethod(name) {
            return `Hello from the method, ${name}!`;
        }
    }
    
    // Main code
    const greeterInstance = new Greeter(); // Creating an instance of the Greeter class
    
    console.log(greetFunction("Alice")); // Using the function to greet
    console.log(greeterInstance.greetMethod("Alice")); // Using the method to greet
                

    Output5

    
    Addition: 15
    Subtraction: 5
        

    Explanation

    • This program demonstrates a function and a class method that both return a greeting message for a given name. 
    • The function and the method are called separately, and the greeting is printed twice using different approaches.
    Summary
    Functions and methods are both blocks of code that perform tasks, but they differ in how they are used. Functions are independent, standalone units that don't rely on objects, while methods are tied to objects or classes and can access or modify object data. Functions are generally used for general-purpose tasks, while methods relate specifically to an object's behavior. Understanding these differences is key to writing modular, organized, and efficient code.By using methods and functions conceptsScholarhat offers training programs such as C programmingCPPC#Java, and Python. You can enroll in any one of them and kickstart your career.

    FAQs

    A function is a block of code that performs a specific task and is called independently, often not tied to any object. A method is similar but is associated with an object or class, operating on the data within that object. Methods require an instance of the class to be called.

     A method is a function that is defined within a class and operates on instances of that class, accessing and manipulating its data. In contrast, a function exists independently and does not belong to any object or class.

    Functions are called methods when they are associated with a class in object-oriented programming (OOP). This terminology emphasizes that these functions are intended to operate on the data contained within class instances (objects), allowing for encapsulation and promoting the principles of OOP, such as abstraction and inheritance.
    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Accept cookies & close this