Module: Object-Oriented Programming Basics

Methods

Java Core: Object-Oriented Programming Basics - Methods

Methods are the building blocks of Java programs. They define a block of code that performs a specific task. They are fundamental to object-oriented programming, allowing you to encapsulate functionality and promote code reusability.

What are Methods?

  • Definition: A method is a block of code that only runs when it is called.
  • Purpose: Methods allow you to break down a complex program into smaller, manageable parts. They help organize code, make it more readable, and reduce redundancy.
  • Association: Methods are associated with a class. They operate on the data (fields/attributes) of the class.
  • Reusability: Once defined, a method can be called multiple times from different parts of the program.

Method Syntax

[access modifier] [static] [return type] method_name([parameters]) {
  // Method body - code to be executed
  // ...
  [return value;] // If the return type is not void
}

Let's break down each part:

  • access modifier: Controls the visibility of the method. Common modifiers:
    • public: Accessible from anywhere.
    • private: Accessible only within the same class.
    • protected: Accessible within the same package and by subclasses.
    • (default/package-private): Accessible within the same package.
  • static: If present, the method belongs to the class itself, not to any specific object of the class. You call it using the class name (e.g., ClassName.methodName()). More on this later.
  • return type: Specifies the data type of the value the method returns. If the method doesn't return a value, the return type is void.
  • method_name: The name of the method. Follows Java naming conventions (starts with a lowercase letter, uses camelCase).
  • parameters: Input values that the method accepts. They are enclosed in parentheses and separated by commas. Each parameter has a data type and a name (e.g., int age, String name). A method can have zero or more parameters.
  • method body: The code that is executed when the method is called. Enclosed in curly braces {}.
  • return value;: If the return type is not void, the method must return a value of the specified type using the return keyword. The return statement also exits the method.

Example

public class Dog {
  String breed;
  int age;

  // Method to set the dog's breed
  public void setBreed(String breedName) {
    breed = breedName;
  }

  // Method to get the dog's age
  public int getAge() {
    return age;
  }

  // Method to make the dog bark
  public void bark() {
    System.out.println("Woof!");
  }

  // Method to calculate the dog's age in human years (example with return value)
  public int ageInHumanYears() {
    return age * 7;
  }

  public static void main(String[] args) {
    Dog myDog = new Dog();
    myDog.setBreed("Golden Retriever");
    myDog.age = 3;

    System.out.println("Breed: " + myDog.breed);
    System.out.println("Age: " + myDog.getAge());
    myDog.bark();
    System.out.println("Age in human years: " + myDog.ageInHumanYears());
  }
}

Explanation:

  • setBreed(String breedName): Takes a String as input and sets the breed field of the Dog object. It has a void return type because it doesn't return a value.
  • getAge(): Returns the value of the age field. It has an int return type.
  • bark(): Prints "Woof!" to the console. It has a void return type.
  • ageInHumanYears(): Calculates the dog's age in human years and returns the result as an int.
  • main(): The entry point of the program. It creates a Dog object, sets its properties, and calls its methods.

Calling Methods

Methods are called using the dot operator (.) on an object of the class.

objectName.methodName(arguments);
  • objectName: The name of the object on which you are calling the method.
  • methodName: The name of the method you want to call.
  • arguments: The values you are passing to the method as input (if the method has parameters).

static Methods

  • Belong to the class: static methods belong to the class itself, not to any specific object.
  • Called using the class name: You call them using the class name followed by the dot operator (e.g., ClassName.staticMethodName()).
  • Cannot access instance variables directly: static methods cannot directly access non-static (instance) variables of the class because they are not associated with a specific object. They can only access static variables.
  • Use Cases: Utility methods, helper functions, or methods that don't require access to object-specific data.

Example:

public class MathUtils {
  public static int add(int a, int b) {
    return a + b;
  }

  public static void main(String[] args) {
    int sum = MathUtils.add(5, 3); // Calling the static method
    System.out.println("Sum: " + sum);
  }
}

Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameters. The compiler determines which method to call based on the number and types of arguments passed.

Example:

public class Calculator {
  public int add(int a, int b) {
    return a + b;
  }

  public double add(double a, double b) {
    return a + b;
  }

  public int add(int a, int b, int c) {
    return a + b + c;
  }

  public static void main(String[] args) {
    Calculator calc = new Calculator();
    System.out.println(calc.add(2, 3));       // Calls add(int, int)
    System.out.println(calc.add(2.5, 3.7));   // Calls add(double, double)
    System.out.println(calc.add(1, 2, 3));    // Calls add(int, int, int)
  }
}

Key Takeaways

  • Methods are essential for organizing and reusing code.
  • Understanding method syntax (access modifiers, return types, parameters) is crucial.
  • static methods belong to the class and are called using the class name.
  • Method overloading allows you to create multiple methods with the same name but different parameters.
  • Methods are the foundation of object-oriented programming and enable encapsulation and modularity.