In Java, Overriding and Overloading are the most extensive used features. First of all we will go through the definitions of both and then we will see the differences.
Overloading:-
In a java class, if two methods have the same name and a different signature, it is known as overloading in Object oriented concepts.
For example, take the case of a Shape Class where you have a method with the name Draw Shape();
This method has two definitions with different parameters.
See the examples below:
1. public void DrawShape(int x1, int y1,int x2,int y2)
{
// draw a rectangle.
}
2. public void DrawShape(int x1,int y1)
{
// draw a line.
}
These two methods do different operations based on the parameters. If you pass 2 parameters to this method line method will be called and executed; if you pass 4 parameters rectangle method will be invoked and that will get exectured. Through the same interface (method name) the user will be able to do multiple tasks (draw a line and rectangle). This is called overloading
One more thing the above is also an example of polymorphism. means exhibiting many forms at a time. isn't it?
Overriding:
Overriding means, to give a specific definition by the derived class for a
method implemented in the base class (Super class).
For example:
Class Rectangle
{
publc void DrawRectangle()
{
// this method will draw a rectangle.
}
}
Class RoundRectangle : Rectangle
{
public void DrawRectangle()
{
//Here the DrawRectangle() method is overridden in the
// derived class to draw a specific implementation to the
//derived class, i.e to draw a rectangle with rounded corner.
}
}
In the above example, the RoundedRectangle class needs to have its own
implementation of the DrawRectangle() method, i.e to draw a rectangle with
rounded corners, so it inherited the Rectangle class and overrided the DrawRectangle method and gave it implementation. This is called Overriding.
Hope you understood this. Please post your comments to discuss.
Subscribe to:
Post Comments (Atom)
0 comments
Post a Comment