Saturday, March 1, 2014

Method : Overloading & Overriding

Method Overloading

Def:  Method  overloading  is  nothing  but  writing  multiple  methods  with  same  name  and
with different arguments.
To overload methods, you should follow the below rules.
  • All of the overloaded methods name should be same.
  • Any  difference  between  the  method  arguments  should  be  maintained.  The difference may be in no. of arguments or the data types of arguments.Finally, when you call the overloaded method, automatically compiler takes the decision that which method is to be called‖, based on the arguments that you are passing.

Download above code for Demo Method Overloading : Download Links

Operator Overloading

Def: Re-defining the functionality of an operator is nothing but "Operator Overloading". With the support of operator overloading, you can use any of the existing operators with the combination of objects.
For example to add two numbers, you write like this (a and b are the variables).
a + b
But suppose you have two objects declared for ―Student‖ class. Then you can‘t write like this:
s1 + s2
Finally,  if  you  want  to  use  the  operator  with  the  combination  of  objects,  you  require "Operator Overloading".
To implement this feature, write the "Operator method" as follows:
public static operator symbol(arguments)
If  you  use  the  specific  operator  with  the  objects,  then  automatically  the  above  method will  be  called  and  the  object(s)  will  be  passed  as  arguments  to  the  above  operator method.

Generally operator method returns a result object.
operator overloading

Download above code for Demo Operator Overloading : Downloads Links

Virtual Methods and Method Overriding

The  similar  operation  as  above  can  be  implemented  with  two  keywords  called  "virtual" and "override". The  "virtual"  keyword  should  be  used  in  the  super  class  method‖  definition  and  the  override keyword should be used in the "sub class method" definition. This concept can be called as “Method Overriding”. In fact, there is no much difference between "Hiding methods" and "Method Overriding". This  is  similar  to  "virtual  functions"  in  C++;  but  "override"  keyword  is  not  required  in
C++. The access modifiers used in the base and derived classes for the virtual methods should
be same.
Method overloading

Download above code for Demo Virtual Methods and Method Overriding : Download Links

No comments:

Post a Comment