Java Reference
In-Depth Information
Type
Description
Static Reference
Uses a static method of an object.
Instance Reference
Uses an instance method of an object.
Arbitrary Object
Method
Used on an arbitrary object of a particular type, rather than a particular
object.
Constructor Referen-
ce
Used to generate a new object by invoking a constructor with the new
keyword.
In the solution, the static method reference type is demonstrated since com-
pareByGoal() is a static method within a static class. It is possible to invoke a
method of an object instance using an instance reference. Consider the following class,
which contains a non-static method for comparing goals within Player objects.
public class PlayerUtility {
public int compareByGoal(Player a, Player b){
int eval;
if(a.getGoals() > b.getGoals()){
eval = 1;
} else if (a.getGoals() < b.getGoals()){
eval = -1;
} else {
eval = 0;
}
return eval;
}
}
This class can be instantiated, and the new instance can be used to reference the
compareByGoals() method, similarly to the technique that was used in the solu-
tion to this recipe.
Player[] teamArray2 = team.toArray(new
Player[team.size()]);
PlayerUtility utility = new PlayerUtility();
Arrays.sort(teamArray2, utility::compareByGoal);
Search WWH ::




Custom Search