اتحاد طلبة هندسة الحاسوب والشبكات - المدونه الرسميه C.N.E : Object Oriented Programming Using Java-7

المشاركات الشائعة

Object Oriented Programming Using Java-7



Overloaded Methods

A method is said to be overloaded when there are more than one copy of that method in the same class. In other words, we have 2 or more methods with the same name, but with different return-data-type or different parameter-lists.

The purpose to have overloading is that
 for example, you sometimes need the method to return an int number in some calling statement & return a double number in another calling statement. Or to pass int numbers in a calling statement & to pass double numbers in another calling statement. 
But a method cannot return more than one data type.

Therefore, the need rises to use overloading to solve this problem.

To understand the principle of overloading, you better consider the following example, which overloads the summation method:

the class
OverClass:


the class
OverClassTest:


The output is:


Note that the compiler chooses one of the methods according to the datatype of the receiving variable (x for example is int variable so the compiler chooses the 1st method in class OverClass),
or the calling statement arguments data types
(the 1st calling statement for example passes 2 integer numbers, so the compiler chooses the 1st method. However, the 2nd calling statement also passes 2 integer numbers!! This way the return type is the only thing to distinguish between overloading methods.
In the case of
void return data type, this way the effect of changing arguments will appear clearly because the compiler will depend only on the arguments to decide which method to choose).

Why character k appears in the output screen?
In case of char data type, the statement return (char)(a+b); will sum the values of a and b in ASCII table and cast the result into char to make it valid to be returned
(The corresponding values of '5' & '6' in ASCII table are 53 & 54 respectively. So, the resulted summation of 107 corresponds to the character k in ASCII table).


سامر المناصرة

 
< >

ليست هناك تعليقات:

إرسال تعليق