As a base for the illustrations presented later in this chapter, we will use a simple utility class able to calculate fibonacci numbers.
The code of the class is:
public class Fibonacci{ public Fibonacci(){ } public long get(int n){ if (n == 0 || n == 1){ return (long) n; } return get(n - 1) + get(n - 2); } public static void main(String[] args){ if (args.length == 0){ System.out.println("Please specify which fibonacci number should be calculated."); System.exit(0); } int theN = Integer.parseInt(args[0]); long theFibonacciNumber = new Fibonacci().get(theN); System.out.println("The fibonacci[" + theN + "] is " + theFibonacciNumber); System.out.println(); long theFibonacciNumberPlusOne = new Fibonacci().get(theN + 1); System.out.println("The fibonacci[" + (theN + 1) + "] is " + theFibonacciNumberPlusOne); } }
This piece of code is pretty straightforward to read: there is one empty constructor to obtain Fibonacci objects references and one unique method to calculate a fibonacci number based on the parameter that represents the one we are interested on.