Saturday, August 13, 2011

OOPs - Polymorphisms

More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding,

Overloading:

public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}

public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}

In overloading , return type does not matter. That means the entire method signature can be different for overloading.

It is a compile time polymorphism - because at the compile time only - depending upon the arguments passed - the method to be called is decided

Overriding:

Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

It is a run time polymorphisiom - as at the run time it is decided which object c is referring to.

ParentClass c = new ChildClass()

Refer - http://ashishbot.blogspot.com/2011/08/override-static-methods-in-java.html

Note - In over riding, the method signature should be exactly same, including the return type.

Ok, now what if it is different? It will then be like overloading in the "child" class.

If Parent p = new Parent(); p.overriddenMethod() -> This will call the parent's method.

No comments:

Post a Comment