Pages

Friday, May 8, 2020

Polymorphism in Java

Index of Polymorphism:

1. What is Polymorphism? Explain with realtime example?
2. How to achieve Polymorphism:
3. What is method overloading. 
4. What is method overriding. 
5. What are Diff. betn method overloading & method overriding. 
6. When to use method overloading in realtime Java Project
7. When to use method overriding in realtime Java Project



1. What is Polymorphism? Explain with realtime example?


Ans --> Different behavior at different instance by using same entity is called as Polymorpohism.

Eg. I am acting as software developer in office and acting as son at home. So here there are my 2 behaviors  software developer and son at 2 different places ie. at Office and home by respectively by using same entity (here I am acting as an entity).
Polymorphism in Java



2. How to achieve Polymorphism?


We can achieve it by using method overloading and method overriding .


Ways to achieve Polymorphism


3) What is METHOD OVERLOADING:


1. In Method overloading, methods name must be same but arguments must be different

2. Private, static, final methods can be overloaded.

3. Not Require Inheritance to achieve Method overloading.

4. No any restrictions for Access modifiers to achieve Method overloading.

5. No any restrictions for Checked and Unchecked exceptions (Exception topic covered separately)

6. No any restrictions for Return types

7. Method overloading also called as Compile time Polymorphism or Early binding or Static binding


Example of Overloading:

class Addition {

     static int add(int a, int b) {
          return a + b;
     }

     static double add(double a, double b) {
          return a + b;
     }
}

class Test {
     public static void main(String[] args) {
          
          System.out.println(Addition.add(11, 11)); // adding int values
          System.out.println(Addition.add(12.3, 12.6)); // adding float values
     }
}




4. What is METHOD OVERRIDING:


1. For Method overriding, methods name and arguments both must be same.

2. Private, static, final methods can NOT override

3. Require Inheritance to achieve method overriding

4. Access modifiers of sub class method must be Same or Stronger than super class method.

5. No any restrictions for Un-checked Exceptions.(Exception topic covered separately)

6. If Sub class method throws Checked exception then it is compulsory that Parent class method throws same or parent exception as of Sub class method else it will give compile time error.  

7. Upto 1.4 version it must be same but since 1.5 version covariant return type can be accepted.(eg given in another section)

8. Method overriding called as Run time Polymorphism or Late binding or Dynamic binding



Example of Overriding:

public class X {

      void m1()
     {
     System.out.println("X.m1"); 
     }
    
}

public class Y extends X
{
    void m1()
{
   System.out.println("Y.m1"); 
}
public static void main(String[] args) {
    
     X x=new Y();  //Dynamic dispatch: which will call all //methods of X class and                                           overridden(similar) methods from Y class.
     x.m1(); 
 }
}



5. What are diff. between method overLOADing and method overRIDing: 

(Most important question as per interview)

METHOD OVERLOADING
METHOD OVERRIDING
1
Same methods name but arguments must be different.
Methods name and arguments must be same.
2
Private, static, final methods can be overloaded
Private, static, final methods can NOT override
3
Not Require Inheritance to achieve
Require Inheritance to achieve
4
No any restrictions for Access modifiers
Access modifiers must be same or Stronger than super class method
5
No any restrictions for checked and unchecked exceptions
No any restrictions for Un-checked.
If Sub class method throws checked exception then it is compulsory that Parent class method throws same or parent exception as of Sub class method else it will give compile time error. 
6
No any restrictions for return types
Upto 1.4 version it must be same but since 1.5 version covariant return type can be accepted.
(eg given in notes)
7
There’s NO any annotation to specify
@Override annotation use to specify overridden method
8
Also called as
Compile time Polymorphism or
Early binding or
Static binding
Also called as
Run time Polymorphism or
Late binding or
Dynamic binding




TypePromotion  **Example of Method Overloading:

class TypePromotion {
    
     void sum(int a, long b) {
          System.out.println(a + b);
     }

     void sum(int a,int b,int c){
     System.out.println(a+b+c);}
 
public static void main(String args[]){

 TypePromotion  obj=new TypePromotion (); 
  obj.sum(20,20);//2nd int literal will be promoted to long 
  obj.sum(20,20,20); 
  } 
}



Type Promotion table:
The data type on the left side can be promoted to right side of it.
byteshortintlong
shortintlong
intlongfloatdouble
floatdouble
longfloatdouble



6. When to use method overloading in Realtime Java Project:


Consider a below scenarios and examples:


class A
{
     public void studentInfo(int age, String loc, int phNo)
  {
     . . . . . .
  }
}

Let’s in this class we have created in 2005.
Now, clients are calling this class as below:

Client 1:

A a = new A();
a. studentInfo(23, "Mumbai", 8888888888);


Client 2:

A a = new A();
a. studentInfo(26, "Pune", 9999999999);

Now suppose in 2010, we get a new requirement of getting an aadhar card of a student. So, what we need to use?


1. First Option: (Add parameter in existing method)

class A
{
 // Increasing parameters in the same method.
    public void studentInfo(int age, String loc, int phNo, int aadharCard)
    {
      . . . . . . 
    }
 }


2. Second Option: (Create new method by adding new parameter with existing)

class A
{
 // another method 
    public void studentInfo(int age, String loc, int phNo, int aadharCard)
    {
      . . . . .
    }
public void studentInfo(int age, String loc, int phNo)
{
   . . . . .
 }
}

So here, our requirement is completed in both cases.

In the 1st option, we will let the client know that the changes done in their existing method. 
The client will say that

1. We don’t want the aadhar card. why should we change our existing code?

2. In future, if any parameters are added, will you be asking us again to change our code?

3. We will need to do lots of testing for these changes. We need to convey our some more clients that to accommodate our change. Please, do not change the methods again and again. Write other methods with different parameters as required, so that we will call separately.



In 2nd option, we will let the client know that the changes in their existing method. They will say:-
1. Ok, we will accommodate but what changes you have appended/done in your existing method?

2. How it will be impacting out on existing code?

3. If everything is the same, the only parameter is changed/increased. So, why you did not give the same name as the method so that we would haven't got confused.


4. So, lots of issues we will be face. 



7. When to use Method overriding realtime:


The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the Super class code.
This is helpful when a class has number of child classes, so if a child class needs to use the Super class method, we can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the Super class code.



NOTE: All interview questions and maximum programs on this topic will be covered in another section. 


No comments:

Post a Comment

**** Please let me know if you have any doubts. ****