How to identify signatures of a method in Java?

1.6k Views Asked by At

I believe that I am having trouble understanding how to give a signature of a method in Java. For example, if my code was:

public void addOn(Fraction other) {
      number = other.denominator * number + other.numerator * denominator;
      denominator = denominator * other.denominator;

and I had to give the signature of the method addOn();

Would the signature for this method simply be addOn(Fraction);?

4

There are 4 best solutions below

2
Vivek Kumar On BEST ANSWER

In Java the method signature contains the name of the method and the data type of the arguments only and nothing else.

For eg in the method posted by you above:

public void addOn(Fraction other) {

}

the signature will be addOn(Fraction ).

This is one of the difference between C++ and java in C++ signature also contains return type but in java return type is not part of method signature. So in case of C++ method signature of above method will be void addOn(Fraction);

0
GhostCat On

That really depends on the level of "accuracy" that you need.

When you informally talk to you coworker, then the "signature" would probably contain all information that a human being might find interesting:

  1. return type
  2. method name
  3. parameter types (including their ordering!)
  4. throws list
  5. ( annotations )

Whereas, when you come from a compiler-constructor or maybe JVM compiler point of view, the answer is different; in that case, only items 2, and 3 do matter; anything else is not part of the signature.

0
Pradeep On

If you want to pass Fraction as parameter to the class. First you need to create reference of Fraction like

Fraction ref =new Fraction();//Assuming Fraction class has default constructor

Then you can pass it as;

addOn(ref);//Ref of Fraction class as parameter

0
Amber Beriwal On

I believe, you should refer this article.

It clearly states that a method signature only contains:

  1. Method Name
  2. Parameter Types, i.e., type and order of parameters

All other parts like exceptions, return types, annotations are part of method declaration not signature.

Along with these syntactical things, semantics should also be considered while choosing a method name.

  • Method name should follow camel casing
  • Method name should be meaningful
  • Method name should start with a verb

I would recommend you to go through java coding guidelines.