Gadgets

Sunday, 17 February 2013

Polymorphism in Java with examples

Polymorphism:-
More than one function with the same is called polymorphism.
There are two types of polymorphisms.
1.      Method overloading (compile time polymorphism).
2.      Method overriding (run time polymorphism).
Method overloading:-
Two or more methods with the same name but difference in methods signatures.
Example:-
void add(int a, int b)  
void add(int a,int b,int c)
  Example program:- 
 public class MethodOverloading {
    public static void main(String args[])
    {
       Sum s=new Sum();
       s.add(10,20);
       s.add(10, 20, 30);
    } 
}
class Sum{
    void add(int a,int b)
    {
               System.out.println("sum of two is"+(a+b));
    }
     void add(int a,int b,int c) {
               System.out.println("sum of three is"+(a+b+c));
    }
}   
Method overriding:-
Two or more methods in super and sub classes with the same name and with same method signatures is called method overriding.
Example:-
public class Boy{
void add(int a,int b){
}
}
class Girl{
void add(int a,int b){
}
}
Example Program:-
public class MethodOverriding {
    public static void main(String args[])
    {
        Sum1 s1=new Sum1();
        s1.add(10, 20);
        s1.add(10, 30);
    }   
}
class Sum1{
    void add(int a,int b){
        System.out.println("sum is:"+(a+b));
    }
}
class Sum2 extends Sum1{
    void add(int a,int b){
        System.out.println("sum is:"+(a+b));
    }
}

No comments:

Post a Comment