• Java Method Overloading

    Java Method Overloading

    In Java Method Overloading, It is possible to create methods that have the same name, but different parameter lists and different definitions. This is called Method Overloading.
    Method overloading is used when objects are required to perform similar tasks but using different input parameters.
    When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which one of the definitions to execute. This process is known as polymorphism.

    To create an overloaded method, all we have to do is to provide several different method definitions in the class, all with the same name, but with different parameter lists. The difference may either be in the number or type of arguments. That is, each parameter list should be unique. Note that the method’s return type does not play any role in this. Here is an example of creating an overloaded method.

    Example :

    //Save This file with the name of class which have main() method.

    import java.lang.*;

    import java.io.*;

    class Rectangle

    {

    int length, width;

    Rectangle() //Default Constructor-1

    {

    length = width = 0;

    }

    Rectangle(int l, int w) //2-Argu. Constructor-2

    {

    length = l;

    width = w;

    }

    Rectangle(int ll)//1-Argu. Constructor-3

    {

    length = width = ll;

    }
    void getdata(int x) //Method-1

    {

    length = x;

    width = x;

    }

    void getdata(int x, int y)//Method-2

    {

    length = x;

    width = y;

    }

    int RectArea()

    {

    int area = length * width;

    return area;

    }

    }

    class ExampleOne

    {

    public static void main(String [] args)

    {

    int ar;

    Rectangle Rct1 = new Rectangle();

    ar = Rct1.RectArea();

    System.out.println(“The are of Rectangle is :” + ar);

    Rectangle Rct2 = new Rectangle(5);

    ar = Rct2.RectArea();

    System.out.println(“The are of Rectangle is :” + ar);

     

    Rectangle Rct3 = new Rectangle(10, 20);

    ar = Rct3.RectArea();

    System.out.println(“The are of Rectangle is :” + ar);

    Rectangle Rct = new Rectangle();

    int x, y;

    x = Integer.parseInt(args[0]);

    y = Integer.parseInt(args[1]);

    Rct.getdata(x, y);

    ar = Rct.RectArea();

    System.out.println(“The are of Rectangle is :” + ar);

    }

    }

    Appreciate my work :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg thisShare on YummlyShare on VKFlattr the authorBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *