Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Method Overloading in Java

In this lesson, you will learn.

  • Compile Time Polymorphism
  • Method Overloading in Java
  • Examples

 

Compile-Time Polymorphism in Java

  • Compile-time polymorphism, also known as static polymorphism or early binding, is a type of polymorphism in Java where the method call is resolved at compile time.
  • This means that the compiler determines which method to execute based on the method signature (name and parameters) during the compilation process.

 

Method Overloading in Java

The most common way to achieve compile-time polymorphism in Java is through method overloading.

Method overloading allows you to define multiple methods in the same class with the same name but different parameters (either in number, type, or order).

     

    Why Method Overloading?

    Method overloading enhances code readability and reusability. Instead of creating multiple methods with different names for similar operations, you can use the same name with different parameters to handle various scenarios. This makes your code more organized and easier to understand.

     

    How Method Overloading Works

    1. Same Name: Methods must have the same name.
    2. Different Parameters: Methods must differ in either:
      • The number of parameters
      • The data type of parameters
      • The order of parameters

     

    Here are various syntax possibilities to achieve method overloading in Java.

    MethodOverloadingJava

     

    1. Different Number of Parameters

    Methods can be overloaded by having a different number of parameters.

    void display(int a) {
        System.out.println("Got an integer: " + a);
    }
    
    void display(int a, int b) {
        System.out.println("Got two integers: " + a + ", " + b);
    }
    

     

    2. Different Types of Parameters

    Methods can be overloaded by having different types of parameters.

    void display(int a) {
        System.out.println("Got an integer: " + a);
    }
    
    void display(String a) {
        System.out.println("Got a string: " + a);
    }
    

     

    3. A Different Ordering of Parameter Types

    If methods have the same number of parameters but in a different order, they are also considered overloaded.

    void display(int a, String b) {
        System.out.println("Integer: " + a + ", String: " + b);
    }
    
    void display(String a, int b) {
        System.out.println("String: " + a + ", Integer: " + b);
    }
    
    

     

    4. Different Types and Number of Parameters

    Combining different types and numbers of parameters offers more overloading options.

    void display(int a) {
    	    System.out.println("Got an integer: " + a);
    	}
    
    	void display(int a, String b) {
    	    System.out.println("Got an integer "
    	    		+ "and a string: " + a + ", " + b);
    	}
    
    	void display(String a, int b, double c) {
    	    System.out.println("Got a string, an integer, "
    	    		+ "and a double: " + a + ", " + b + ", " + c);
    	}
    

     

    Example 1: Method Overloading

    package ch7;
    
    class OverloadingDemo {
    	
    	void demo() {
    		System.out.println("No Parameters");
    	}
    	
        void demo(int a) {
            System.out.println("a: " + a);
        }
    
        void demo(int a, int b) {
            System.out.println("a and b: " + a + "," + b);
        }
    
        double demo(double a) {
            System.out.println("double a: " + a);
            return a*a;
        }
    }
    
    class MethodOverloadingEx1 {
        public static void main(String args[]) {
        	
            OverloadingDemo Obj = new OverloadingDemo();
            double result;
            Obj.demo();
            Obj.demo(10);
            Obj.demo(10, 20);
            result = Obj.demo(5.5);
            System.out.println("Square: "+result);
        }
    }
    

    Output

    No Parameters
    a: 10
    a and b: 10,20
    double a: 5.5
    Square: 30.25
    

     

    Example 2: Method Overloading

    package ch7;
    
    public class MethodOverloading {
    
        public void greet() {
            System.out.println("Hello!");
        }
    
        public void greet(String name) {
            System.out.println("Hello, " + name + "!");
        }
    
        public void greet(String firstName, String lastName) {
            System.out.println("Hello, " + firstName 
            		+ " " + lastName + "!");
        }
    
        public static void main(String[] args) {
        	MethodOverloading example = new MethodOverloading();
    
            example.greet(); // Calls first method
            example.greet("John"); // Calls second method
            example.greet("John", "Doe"); // Calls third method
        }
    }
    

    Output

    Hello!
    Hello, John!
    Hello, John Doe!
    

     

    Bonus!

    Exercise: Payment Process System

    Background

    Imagine you are developing a part of a payment processing system for an e-commerce application. The application needs to handle different types of payments: by cash, by credit card, and by digital wallet. Each payment method requires slightly different information:

    • Cash payments only need to know the amount.
    • Credit card payments need the amount, card number, expiry date, and CVV.
    • Digital wallet payments need the amount, wallet ID, and an optional authorization token for additional security.

    Task

    Create a PaymentProcessor class that overloads the processPayment method to handle these three types of payments with the appropriate parameters for each.

    Requirements

    1. Cash Payment Method: Should accept a single parameter for the amount.
    2. Credit Card Payment Method: Should accept parameters for the amount, card number, expiry date, and CVV.
    3. Digital Wallet Payment Method: Should accept parameters for the amount, wallet ID, and an optional authorization token. The authorization token should be optional; if not provided, assume a default token.

     

    Solution

    package ch7;
    
    public class PaymentProcessor {
    
        // Method for processing cash payment
        public void processPayment(double amount) {
            System.out.println("Processing cash payment of $" + amount);
        }
    
        // Method for processing credit card payment
        public void processPayment(double amount, String cardNumber, 
        		String expiryDate, int cvv) {
            System.out.println("Processing credit card payment of $" 
        		+ amount + " using card number " + cardNumber);
        }
    
        // Overloaded method for processing digital wallet 
        // payment without authorization token
        public void processPayment(double amount, String walletID) {
            processPayment(amount, walletID, "DEFAULT_TOKEN");
        }
    
        // Overloaded method for processing digital wallet 
        // payment with authorization token
        public void processPayment(double amount, String walletID, 
        		String authToken) {
            System.out.println("Processing digital wallet payment of $" 
        		+amount+ " using wallet ID " + walletID + 
        		" with auth token " + authToken);
        }
    
        public static void main(String[] args) {
            PaymentProcessor processor = new PaymentProcessor();
            
            // Cash payment
            processor.processPayment(100.0);
            
            // Credit card payment
            processor.processPayment(250.0, "1234567890123456", "12/25", 123);
            
            // Digital wallet payment without auth token
            processor.processPayment(75.0, "wallet123");
            
            // Digital wallet payment with auth token
            processor.processPayment(150.0, "wallet456", "AUTH123");
        }
    }
    

    Output

    Processing cash payment of $100.0
    Processing credit card payment of $250.0 using card number 1234567890123456
    Processing digital wallet payment of $75.0 using wallet ID wallet123 with 
    auth token DEFAULT_TOKEN
    Processing digital wallet payment of $150.0 using wallet ID wallet456 
    with auth token AUTH123
    
    

     


     

    End of the lesson….enjoy learning

     

     

    Student Ratings and Reviews

     

     

     

    There are no reviews yet. Be the first one to write one.

     

     

    Submit a Review