Skip to Content
bytegarden

Methods

  • Methods are members of classes that provide functionality (behavior) for the class. They are the Java equivalent of functions in other programming languages, but with object-oriented principles applied.
  • Early (Monolithic) programming involved writing programs as a single piece, making large codebases difficult to manage and limiting maintainability.
  • Benefits in OOPS:
    • Functions in classes are called methods
    • Better organization for large-scale software
    • Enhanced maintainability

Method Structure

Method declaration

  • Method Header or Signature of a method
  • Access Specifier (modifier): Controls where the method can be accessed from. Common access modifiers are (Least to Most Restrictive):
    • public: Accessible from any other class
    • protected: Accessible within its own package and by subclasses
    • (default): Accessible within the same package
    • private: Accessible only within the class it is defined

Types of Methods

  1. Instance Methods (Non-Static):
    1. Requires creating an object instance to be called
    2. Can access both static and non-static members
    3. These methods can access and modify instance variables
    4. Associated with an instance of a class
  2. Static Methods:
    1. using the static keyword
    2. Can only directly access other static members
    3. Can be called without creating an object
    4. Belong to the class itself rather than instances
// example of methods
public class Calculator {
    // Instance method
    public int multiply(int a, int b) {
        return a * b;
    }

    // Static method
    public static int subtract(int a, int b) {
        return a - b;
    }
}
// Usage
public class Main {
    public static void main(String[] args) {
        // Calling static method
        int difference = Calculator.subtract(10, 4);

        // Calling instance method
        Calculator calc = new Calculator();
        int product = calc.multiply(4, 5);
    }
}

Important Considerations for Return Types

  1. Memory Management
    1. Returned objects remain in heap memory
    2. Garbage collector handles cleanup when no references remain
    3. Method local variables are destroyed after method execution
  2. String Immutability
    1. Strings are immutable in Java
    2. String methods always return new String objects
    3. Original String objects are never modified
  3. Return Type Rules
    1. Must match declared return type exactly
    2. Can return subtypes of declared return type
    3. Cannot return multiple values directly (use container objects or arrays)

Common Pitfalls to Avoid

  1. Returning References to Private Data

    // BAD - exposes internal array
    private int[] data;
    public int[] getData() {
        return data;
    }
    
    // GOOD - returns copy
    public int[] getData() {
        return Arrays.copyOf(data, data.length);
    }
  2. Null Returns

    1. Avoid returning null when possible
    2. Use empty collections instead of null for collections
    3. Consider using Optional<T> for potentially absent values
  3. Parameter Modification

    1. Document any modifications to parameters
    2. Make defensive copies of mutable parameters if necessary

Methods and Parameters

Method Invocation Terminology

  • Calling Method (Caller): The method that invokes another method
  • Called Method: The method being invoked
  • Parameters/Arguments: Values passed between methods

Parameter Types

  • Formal Parameters: Parameters declared in the method or a function definition (inside the called method). Syntax:

    function_name(datatype variable_name)
  • Actual Parameters (Arguments): Parameters passed in the method or function call (inside the calling method). Syntax:

    func_name(variable name(s));
  • Input: Parameters passed to the method (inside parenthesis of first line)

  • Output: Return value from the method

Parameter Passing

  • The contents of actual parameters are copied into formal parameters i.e formal parameters reference to the object that is created for actual parameters.
  • For objects (reference types), the reference (memory address) is copied, so both variables point to the same object. Changes to the object through either variable affect both.
  • For primitive types (e.g., integers, floats, booleans), the actual value is copied, so each variable holds its own copy. Changes to one variable do not affect the other.
  • Java supports 2 types of paramenter passing techniques:
    1. Call-by-value
    2. Call-by-reference

Method Overloading

  • It is a feature in Java that allows you to define multiple methods with the same name but with different parameter lists. This enables you to perform similar operations with different types or numbers of parameters. See method overloading example (overloading.java, below)

    Overloading.java
    // program to demonstrate method overloading
    public class Overloading {
        // this method is being compared with the other two methods
        public int max(int x, int y) {
            return (x > y) ? x : y;
        }
        
        // Different Data Types (Method for float values)
        public float max(float x, float y) {
            return (x > y) ? x : y;
        }
    
        // Different Number of Parameters (Method for three integers)
        public int max(int x, int y, int z) {
            return (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
        }
    }

    It has no main method; it only shows the overloaded methods. Run it on your computer with java Overloading.java.

    Java 21

Rules for Overloading

  1. Methods must have the same name
  2. Methods must have different parameter lists through either:
    1. Different data types of parameters
    2. Different number of parameters

Method Overriding

Always use @Override annotation. Clearly indicates intention to override.

  • Overriding means having two methods with the same name and parameters: one in the parent class and one in the child class. It allows the child class to provide a specific implementation for a method already defined in the parent class

  • At runtime, the actual object type determines which overridden method is used, while the reference type determines the overloaded method at compile time

  • Polymorphism applies to overriding, not to overloading

  • Overriding is a run-time concept (Dynamic Binding) while overloading is a compile-time concept (Static Binding)

  • Overriding in Inheritance (example (OverridingInherit.java, below))

    • The overridden method in subclass has the same signature as the superclass method
    OverridingInherit.java
    // program to demonstrate overriding within inheritance in Java
    class Super {
        void display() {
            System.out.println("Hello");
        }
    }
    
    class Sub extends Super {
        void display() {                  // Overriding the display method
            System.out.println("Hello Welcome");
        }
        void function1() {                  // Overriding the display method
            System.out.println("Hello asd");
        }
    }
    
    public class OverridingInherit {
        public static void main(String[] args) {
            Super su = new Super();       // Superclass object
            su.display();                 // Prints "Hello"
    
            System.out.println("----------");
    
            Sub sb = new Sub();           // Subclass object
            sb.display();                 // Prints "Hello Welcome"
            sb.function1();
            System.out.println("----------");
    
            Super s = new Sub();          // Superclass reference to subclass object
            s.display();                  // Prints "Hello Welcome"
            // The display() method from Sub class is called due to method overriding - this
            // demonstrates runtime polymorphism where the JVM determines which method to
            // execute based on the actual object type, not the reference type
        }
    }
    Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ
  • When a subclass inherits from a superclass:

    • It initially gets all methods from the superclass
    • If it overrides a method, the superclass version is “shadowed” or hidden
    • Only one version of the method can be active - the subclass version takes precedence

Overriding v/s Overloading

FeatureMethod OverloadingMethod Overriding
TimingCompile-timeRun-time
ParametersMust be differentMust be same
Return TypeCan be differentMust be same (or covariant)
ScopeSame class or inheritanceOnly through inheritance
BindingStatic bindingDynamic binding
Method ResolutionBased on parameter listBased on object type

Static Binding v/s Dynamic Binding

AspectStatic BindingDynamic Binding
Resolution TimeCompile-timeRun-time
Method TypeFinal, static, private methodsVirtual/overridden methods
PerformanceFasterRelatively slower
PolymorphismMethod overloadingMethod overriding
ExampleMath.max(10, 20)animal.makeSound() where animal could be Dog/Cat
Type CheckingBased on reference typeBased on object type
MemoryLess memoryMore memory (virtual table)
Also Known AsEarly bindingLate binding

Dynamic Method Dispatch (or run-time polymorphism)

  • Definition: When a superclass reference holds a subclass object and an overridden method is called
  • Definition: A runtime mechanism where Java determines which method implementation to call based on the actual object type rather than the reference type
  • Key Rule: Method call is determined by the actual object type, not the reference type
  • When a subclass overrides a method from its superclass, the overridden method in the subclass is executed when called on an instance of the subclass, even if the reference to the object is of the superclass type
  • For example, the overridden method in superclass becomes hidden for subclass objects
  • A superclass reference can have an object of subclass
Superclass_name s = new Subclass_name();
  • A subclass reference cannot have an object of superclass
Subclass_name su = new Superclass_name();

Variable Arguments (Varargs)

  • Eliminates the need for method overloading when you want to handle different numbers of parameters of the same type
  • Varargs parameter is treated as an array internally
  • ... converts multiple arguments into an array
public static void printNumberOfArguments(int... numbers) {
    System.out.println(numbers.length);
}

// Usage examples: (prints length i.e no. of arguments passed)
// can pass either multiple arguments or an array directly
printNumberOfArguments();
printNumberOfArguments(1);
printNumberOfArguments(1, 2);
printNumberOfArguments(new int[] { 1, 2, 3, 4 });

Rules

  • Must be the last parameter in the method

  • Only one varargs parameter allowed per method

  • Can combine with regular parameters:

    public void show(int required, int... optional) {
        // 'required' is mandatory
        // 'optional' can have 0 or more values
    }

Advantages of Varargs

  1. Flexibility

    • Handle varying numbers of parameters
    • No need for multiple overloaded methods
  2. Clean Code

    • Reduces code duplication
    • More maintainable than multiple overloaded methods
  3. Backward Compatibility

    • Works with existing array-based code
    • Seamless integration with legacy systems