Posted by: ahmedashfaque | April 29, 2015

difference between method overloading and method overriding in Java


In Java there are 2 powerful ways to implement different interfaces to work with the same class. This prevents creation of too many unnecessary classes and thus improves code reuse. These techniques include method overloading and method overriding. Let us see them in action.

Let us have an example of method overloading first.

public class rectangle {

private integer length;

private integer height;

private integer x;

private integer y;

 

public rectangle() {

this.x = 15;

this.y = 20;

this.length = 20;

this.height = 25;

}

 

public rectangle (integer length1, integer height1) {

this.length = length1;

this.height = height1;

}

 

public rectangle (integer length2, integer height2, integer x, integer y) {

this.length = length2;

this.height = height2;

this.x = x;

this.y = y;

}

}

Using this technique you can create many different objects from the same class.

Rectangle rectangle1 = new rectangle();

Rectangle rectangle2 = new rectangle(25,30);

Rectangle rectangle3 = new rectangle(30, 35, 5, 10);

You can see that we have created 3 objects which do different computations even though the base class is the same.

When you test your code, you will see that 3 objects will be created. A rectangle1 will be created with a length of 20 and a height of 25 with a center on (15, 20) coordinates, rectangle2 will be created with length of 25 and height of 30 with a center on (15, 20) coordinates and a rectangle3 will be created with a length of 30 and a height of 35 and center of the rectangle will be at (5, 10) coordinates.

Now let us see method overriding:

class Animal{

void run(){System.out.println(“Animal is eating”);}

}

class Cat extends Animal{

void run(){System.out.println(“Cat is eating mouse”);}

 

public static void main(String args[]){

Cat obj = new Cat();

obj.run();

}

 

When you run your code, you will see that you will get a different result than what is defined in the parent class. You can see that method overriding works at class level and it completely suppresses methods defined in the parent class. In contrast method overloading works at method level and depending on usage, one method will be used and other similar methods will be overlooked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: