Java Program to Demonstrate Method Overloading with Normal Method Invocation
Java Program to Demonstrate Method Overloading with Normal Method Invocation

Java Program to Demonstrate Method Overloading with Normal Method Invocation

If we use multiple methods having the same name in a single class, then the concept is called method overloading. Creating methods with the same name can create ambiguity for the compiler, so we have to change either the return types or parameter lists of those methods. In this program, I am showing method overloading with the getdata() method. getdata() method is differentiated by parameter lists. All the getdata() methods are used here to initialize data members of the Box class.

Another normal method is been invoked here for user-inputted values. Using scanner class we can take user inputs and that is also displayed in this program.

import java.util.Scanner;
class Box //normal class
{
    private int length,breadth,height; //data members
    void getdata() //default method
    {
        length=breadth=height=1;
    }
    void getdata(int x) //parameterized method
    {
        length=breadth=height=x;
    }
    void getdata(int x,int y,int z) //parameterized method [constructor overloading]
    {
        length=x;
        breadth=y;
        height=z;
    }
    int takedata() //normal method for user inputs
    {
        System.out.println("Enter the length,breadth,height : ");
        Scanner Sc=new Scanner(System.in);
        length=Sc.nextInt();
        breadth=Sc.nextInt();
        height=Sc.nextInt();
        return (length*breadth*height);
    }
    void display()
    {
        System.out.println("Volume of the Boxes : "+(length*breadth*height));
    }
}
public class MainBox
{
    public static void main(String args[])
    {
        Box b1=new Box();
        b1.getdata();
        b1.display();
        Box b2=new Box();
        b2.getdata(5);
        b2.display();
        Box b3=new Box();
        b3.getdata(3,4,5);
        b3.display();
        Box b4=new Box();
        int volume=b4.takedata();
        System.out.println("Volume of the user inputted box is : "+volume);
    }
}

The output of the above program is given here:

Output-method overloading