/* related posts with thumb nails */

Differences between overloading and overriding:

· Method overriding is writing a member function in a derived class with the same name and signature of an existing member function of the base class.

· In such cases, the member function of the derived class is called with the objects of the derived class.

· Method overriding takes place only when a method with same signature is present in both parent and child class.

· We use this when we want an object of child class to behave in different fashion with a same method name.

Following are the differences between method overloading and method overriding.

Method Overloading

Method Overriding

It allows you to have any number of functions with the same name provided they take different number of arguments or different types of arguments.

If a function with same signature is present both in parent and child classes, with the instances of child classes; child class methods are called.

Function signature is different

Function signature is same

Scope of the overloading methods can be in a same class; or one in sub class and the other in child class.

Scope of the overriding methods is different i.e. one is present in parent class and the other is present in child class.

Here, we expect same behavior but on different operands.

Here, we expect different behavior (modified version) but with the same method name. This is also known as redefinition.

Example:

class one

{

public void show()

{

System.out.println( “hello one”);

}

public void show1()

{

System.out.println(“hello”);

}

public void show1(int x)

{

System.out.println(“overloading demo”);

}

}

class two extends one

{

public void show()

{

System.out.print(“ Overriding demo:”);

System.out.print(“ hello two”);

}

}

class Test

{

public static void main(String as[])

{

two t1 =new two();

t1.show(); // prints “Overriding demo: hello two”

}

}

Explanation:

In the above example,

There is an overloaded function “show1(int)”, because there is already another function with the same name without arguments.

Also, we have written an overriding method “show ()” in derived class with the same name and signature as that of “show ()” method in base class. With the object “t1” derived class “show()” is called and “Overriding demo: hello two” is printed on the screen.

Related Topics:

0 comments:

Post a Comment