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
Giz
with 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 Giz
parameter. The second method gets aGiz
parameter that is not final this time, sets it to a new instance ofGiz
and calls itsfunc()
method. FinalArguments
also has methodg(final int i)
that increaments ani
by 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 inti
ing(final int i)
method or set a new instance ofGiz
to agrumentGiz g
inwith(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.