View RSS Feed

My Java Tips

Method signatures

Rate this Entry
by , 11-21-2011 at 04:52 PM (814 Views)
In this post, I will present an interesting example related to method signature.


Method signature comprise of the following:

- method name
- return type
- input parameters
- access modifier

For example:

Java Code:
public Vector processText(String test, int id)
Two methods in a class can have same name provided then have different parameters. Different parameters means different no of parameters and it can also be parameters with different datatypes. For example:

Java Code:
public Vector processText(String test, int id)
{…}
public Vector processText(String test, int id, boolean valid)
{…}
The example presented above is perfectly valid as even both methods have same name, but number of parameters are different.

What if we have methods with same names, same no of parameters and all the variables have same datatype but the return type is different? Interesting question. Read the next post for the answer.




Answering the raised question: Some of you might think it is ok to have methods with same names, same no of parameters and all the variables have same datatype but with different since JRE will know which method to call depending on the variable that will get the value returned by the method.

Some of you might this that it is a run time error.

The answer is: it’s a compile time error. Let me give you an example:

Java Code:
public  int getValue(int a)
{
System.out.println("I m in int getValue(int)");
return 1;
}

public  float getValue(int a)
{
System.out.println("I m in float getValue(int)");
return 1.5f;
}
Error:


Exception in thread "main" java.lang.Error: Unresolved compilation problem

Actually, Java compiler treats both method same and duplicate method declaration is not allowed.

I hope I was able to provide interesting example.

Happy coding.

Submit "Method signatures" to Facebook Submit "Method signatures" to Digg Submit "Method signatures" to del.icio.us Submit "Method signatures" to StumbleUpon Submit "Method signatures" to Google

Comments