Pages

get our extension

Search program

Monday, 12 August 2013

Example Program of Method overloading and Method overriding

Example of method overloading:-

//dynamic polymorphism

class Sum
{
void add(int a, int b)
{
            System.out.println("Sum of two="+(a+b));
}

void add(int a, int b,int c)
{
            System.out.println("Sum of three="+(a+b+c));
}
}
class Polymorphism
{
      public static void main(String args[])
      {
            Sum s=new Sum();
            
            s.add(10,15);
         s.add(10,20,30); 
   }
 }

Output:-

Sum of two=25
Sum of three=60


è That means, JVM decides which method is called depending on the difference in the method signature.

Example of method overriding:-

//dynamic polymorphism

class A
{
void cal(double x)
{
            System.out.println("square value="+(x*x));
}
}
class B extends A
{
void cal(double x)
{
            System.out.println("square root="+Math.sqrt(x));
}
}
class Polymorphism
{
      public static void main(String args[])
      {
            A a=new A();
           
            a.cal(15);             
  }                   
} 
  
Output:-
square value=225.0                                                     
è When we create object of class B(B a=new B()), then out will be
square root=3.872983346207417

è That means JVM decides which method is called depending on the data type (class) of the object used to call the method.