class
Final arguments to function – Part 2
In this example we shall show you how to use final arguments to a function. To use final arguments to a function we have performed the following steps:
- We have created a class
Gizwith a methodfunc(). - We have also created a class
FinalArguments, that has a methodwith(final Giz g)and another methodwithout(Giz g). The first method uses afinal Gizparameter. The second method gets aGizparameter that is not final this time, sets it to a new instance ofGizand calls itsfunc()method. FinalArgumentsalso has methodg(final int i)that increaments aniby one and returns it.- Since
with(final Giz g)andg(final int i)methods have final arguments they cannot change them. For example we cannot set a different value to final intiing(final int i)method or set a new instance ofGizto agrumentGiz ginwith(final Giz g)method,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
class Giz {
public void func() {
}
}
public class FinalArguments {
void with(final Giz g) {
//! g = new Gizmo(); // Illegal -- g is final
}
void without(Giz g) {
g = new Giz(); // OK -- g not final
g.func();
}
// void f(final int i) { i++; } // Can't change
// You can only read from a final primitive:
int g(final int i) {
return i + 1;
}
public static void main(String[] args) {
FinalArguments bf = new FinalArguments();
bf.without(null);
bf.with(null);
}
}
This was an example of how to use final arguments to a function in Java.
