Polymorphism

Java support two types of polymorphism
1-Run-time polymorphism
2-Compile-time polymorphism

Compile-time polymorphism - Overloading
1.) The number of parameters is different for the methods.

2.) The parameter types are different (like changing a parameter that was a float to an int)

public class chooseWhatDo(){
   public iDoMyChoice(String s){
       //Do Your choice
}
 public iDoMyChoice(float f){
       //Do Your choice
}
 public iDoMyChoice(int i, float f){
       //Do Your choice
}
}

Run-time polymorphism - Overriding
when the class inherit the parent class and overrides its some features

class Father{
       public void message() {
              System.out.println("its happes i am old and no one cares");
       }
}

public class child extends Father{
       @Override  // @Override annotation in Java 5 is optional but helpful.
       public void message() {
              System.out.println("take my new features");
       }

}


Before java 5.0 when you overrides a method both parameter and return types must match exactly -- but after java 5.0 its support the covariant return types
also method can return the subtype of the object of type returned by parent class method, which it overrides  

static method can be overloaded
but static method can not be override, you can override no error but not get its feature.


Some Ques-
1- Father f = new Father();
     f.message(); // will call the message of father 

2- Father f = new Child();
     f.message(); // will call the message of child

3- Child f = new Child();
     f.message(); // will call the message of child

3- Child f = new father(); // Compile time Error
 

the Every constructor run in the hierarchy when you create the instance of  any concrete child 
class 
call to super and other constructor of the class must either be first statement of the class not both 

Note - The sequence on execution block
Static block - at the time of class load 
initialization block  - after call to super - all in the hierarchy
constructor block

public class MaBase {
MaBase (){
System.out.println("in base constructor");
}

{
System.out.println("initialization base block");
}

static{
System.out.println("static bloc base  block");
}
}

public class MaChild extends MaBase{
{
System.out.println("initialization block");
}
 static{
System.out.println("static bloc  block");
}
MaChild (){
System.out.println("in child");
}
public static void main(String[] args) {
MaBase mb = new MaChild();
MaChild  m = (MaChild)  mb;
}
}


Output - 
static bloc base  block
static bloc  block
initialization base block
in base constructor
initialization block
in child


Comments