Implementation of Java method overloading (changing the data types)
KW.java
class Area
{
    static int rectangle(int a,int b)
    {
        return a*b;
    }
    static double rectangle(double a,double b)
    {
        return a*b;
    }
}

class KW
{
    public static void main(String args[])
    {
        System.out.println("Area of Rectangle "+Area.rectangle(3.14,10.0)); 
        System.out.println("Area of Rectangle "+Area.rectangle(5,10)); 
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Area of Rectangle 31.400000000000002 Area of Rectangle 50 kodingwindow@kw:~$
Implementation of Java method overloading (changing the number of arguments)
KW.java
class Area
{
    static int rectangle(int a,int b)
    {
        return a*b;
    }
    static int rectangle(int a)
    {
        return a*a;
    }
}

class KW
{
    public static void main(String args[])
    {
        //Every square is rectangle
        System.out.println("Area of Square "+Area.rectangle(5)); 
        System.out.println("Area of Rectangle "+Area.rectangle(5,10)); 
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Area of Square 25 Area of Rectangle 50 kodingwindow@kw:~$
Advertisement