Computer Applications
How does the compiler interpret more than one definitions having same name ? What steps does it follow to distinguish these ?
User Defined Methods
6 Likes
Answer
The compiler interprets more than one definitions having same name by matching the signature in the function definitions with the arguments given in the method call statement.
When a function name is declared more than once in a program, the compiler will interpret the second and subsequent declarations as follows:
- If the signatures of subsequent functions match the previous function's, then the second is treated as a re-declaration of the first and is flagged at compile time as an error.
- If the signatures of the two functions match exactly but the return types differ, the second declaration is treated as an erroneous re-declaration of the first and is flagged at compile time as an error. For example:
float square(float f) {...}anddouble square(float x)will be treated as an error.
Functions with the same signature and same name but different return types are not allowed in Java. We can have different return types, but only if the signatures are also different :float square (float f)anddouble square (double d) - If the signatures of the two functions differ in either the number or type of their arguments, the two functions are considered to be overloaded.
Answered By
4 Likes
Related Questions
Write a complete Java program that invokes a function satis() to find whether four integers a, b, c, d sent to satis( ) satisfy the equation a3 + b3 + c3 = d3 or not. The function satis( ) returns 0 if the above equation is satisfied with the given four numbers otherwise it returns -1.
Write a program that uses a method power( ) to raise a number m to power n. The method takes int values for m and n and returns the result correctly. Use a default value of 2 for n to make the function calculate squares when this argument is omitted. Write a main( ) method to get the value of m and n to display the calculated result.
Discuss how the best match is found when a call to an overloaded method is encountered. Give example(s) to support your answer.
Design a class to overload a function area( ) as follows:
- double area (double a, double b, double c) with three double arguments, returns the area of a scalene triangle using the formula:
area = √(s(s-a)(s-b)(s-c))
where s = (a+b+c) / 2 - double area (int a, int b, int height) with three integer arguments, returns the area of a trapezium using the formula:
area = (1/2)height(a + b) - double area (double diagonal1, double diagonal2) with two double arguments, returns the area of a rhombus using the formula:
area = 1/2(diagonal1 x diagonal2)
- double area (double a, double b, double c) with three double arguments, returns the area of a scalene triangle using the formula: