Comp 110 Method Definition & "Signatures"

Method Definition Syntax

The general format for a method definition is:

<visibility> <returnType> <methodName>(<typeA> <paramA>, <typeB> <paramB>, ...) {
  <method body statements>
}

Now take our concrete example:

public int timesThree(int a){
    return 3*a;
}

In the "timesThree()" method, "public" is our visibility, "int" is our return type, "timesThree" is our method name, and "int a" is our parameter. Let's explore what these mean. 


Visibility

The visibility field, or its access modifer determines which class has the ability to access our method. There are two access modifiers that we learned about so far. 

publicA class, method or constructor declared public can be accessed from any other class.
privateA class, method or constructor declared private can only be accessed from its own class. 

There are also the default and protected access modifiers, which you can learn more about here.

Return Type

return type tells us the type of data that our method will output. The timesThree method below tells us that our method will return an integer. 

public int timesThree(int a){
    return 3*a;
}

If we decided to return the String "45", eclipse would give us an error. This is because there is a type mismatch.  If timesThree is expected to return an integer, but returns a String, the program would not run. The way to fix this is to match the output with the return type.

//BAD CODE
public int timesThree(int a){
    return "45";
}

Some common return types include String, double, int, and void. The void return type specifies a method which has no output. It is the only method type which does not return anything. 

Parameters

Parameters specify the input of our method. We can have no parameters, one parameter, two, three, or thirty. The below method takes no input:

public String sayHello(){
    return "hello!";
}

We can call it as such: 

String foo = this.sayHello();

This method takes 5 inputs:

public int add5(int a, int b, int c, int d, int e){
    return a + b + c + d + e;
}

We can call it as such: 

System.out.println( this.add5(1, 2, 3, 4, 5) );
//Prints 15 to the console