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.


10 comments:

  1. Well....it is explained very clearly and was quite simple to understand!! Thanks a lot!

    ReplyDelete

  2. Latest Govt Bank Jobs Recruitment Notification 2016


    A big thank you for your post.Really looking forward to read more. Much obliged......................

    ReplyDelete
  3. new horizon security service I am really impressed with your efforts and really pleased to visit this post.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    hyperion financial management training in chennai

    ReplyDelete
  6. That is a brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at our dot net training institute in Chennai. Thanks a lot. Keep writing more on dot net course in Chennai, would love to follow your posts and refer to others in dot net training institutes in Chennai.

    ReplyDelete
  7. best franchise to own I would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks

    ReplyDelete