3

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 Answers4

3

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

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);

Vivek Kumar
  • 360
  • 1
  • 7
  • 16
  • Argument type covers that also because in case the method is method(int a, String b) then for this method signature will be method(int, String) which is already taking care of the order, as after changing the order i.e method(String, int) the argument type changes as well/ – Vivek Kumar Sep 08 '16 at 14:38
  • 1
    Above code would be problem as number is not initialized – Amber Beriwal Sep 08 '16 at 14:43
1

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

halil
  • 800
  • 16
  • 33
Pradeep
  • 1,947
  • 3
  • 22
  • 45
0

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.

Amber Beriwal
  • 1,568
  • 16
  • 30