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 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
- Instance Methods (Non-Static):
- Requires creating an object instance to be called
- Can access both static and non-static members
- These methods can access and modify instance variables
- Associated with an instance of a class
- Static Methods:
- using the
statickeyword - Can only directly access other static members
- Can be called without creating an object
- Belong to the class itself rather than instances
- using the
// 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
- Memory Management
- Returned objects remain in heap memory
- Garbage collector handles cleanup when no references remain
- Method local variables are destroyed after method execution
- String Immutability
- Strings are immutable in Java
- String methods always return new String objects
- Original String objects are never modified
- Return Type Rules
- Must match declared return type exactly
- Can return subtypes of declared return type
- Cannot return multiple values directly (use container objects or arrays)
Common Pitfalls to Avoid
-
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); } -
Null Returns
- Avoid returning null when possible
- Use empty collections instead of null for collections
- Consider using
Optional<T>for potentially absent values
-
Parameter Modification
- Document any modifications to parameters
- 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:
- Call-by-value
- 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
- Methods must have the same name
- Methods must have different parameter lists through either:
- Different data types of parameters
- 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

| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Timing | Compile-time | Run-time |
| Parameters | Must be different | Must be same |
| Return Type | Can be different | Must be same (or covariant) |
| Scope | Same class or inheritance | Only through inheritance |
| Binding | Static binding | Dynamic binding |
| Method Resolution | Based on parameter list | Based on object type |
Static Binding v/s Dynamic Binding
| Aspect | Static Binding | Dynamic Binding |
|---|---|---|
| Resolution Time | Compile-time | Run-time |
| Method Type | Final, static, private methods | Virtual/overridden methods |
| Performance | Faster | Relatively slower |
| Polymorphism | Method overloading | Method overriding |
| Example | Math.max(10, 20) | animal.makeSound() where animal could be Dog/Cat |
| Type Checking | Based on reference type | Based on object type |
| Memory | Less memory | More memory (virtual table) |
| Also Known As | Early binding | Late 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
-
Flexibility
- Handle varying numbers of parameters
- No need for multiple overloaded methods
-
Clean Code
- Reduces code duplication
- More maintainable than multiple overloaded methods
-
Backward Compatibility
- Works with existing array-based code
- Seamless integration with legacy systems