Polymorphism


What is polymorphism?

Polymorphism is one of the highly used concept of OOPS . It gives us the ultimate flexibility in extensibility. Polymorphism is a term that describes a situation where one name may refer to different methods. In java there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with

·        Different method signature and different number/type of parameters.

·        Same method signature but different number of parameters.

·        Same method signature and same number of parameters but of different type

 

int add(int a,int b)

     float add(float a,int b)

     float add(int a ,float b

     void add(float a)

     int add(int a)

     void add(int a)                 //error conflict with the method int add(int a)

 

Overloading is determined at the compile time.

 

Advertisements

Use of final keyword


I have seen that final keyword mainly can be used with

1)      Class level variable

2)      method

3)      class

4)      Objects

 

1) If a final is assigned to a variable , the variable becomes a constant. It means that the value of variable once assigned  cannot be changed. The variable behaves like a

final int i=0;

i =5; // error

 

2) If a final is assigned to a method than it cannot be overridden in its child Class.

 

Class Parent {

 

Public final void print(){

 

            System.out.println(“Inside”);

}

}

 

Class Child extends Parent{

 

Public final void print(){             // error cannot override final method

 

            System.out.println(“Inside”);

}

}

 

3) If a class is made as final, then no other class can extend it and make it as parent class. Eg String,Integer

 

4) final objects are instantiated only once. i.e

 

final Map map = new HashMap();

 

map.put(“key”,”value”);

 

map = new HashMap();  // error