class
Final arguments to function
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 class
FinalArgs
, that hasrun()
method and amyFunc(final Calendar d)
method. - The first method calls the second one, that uses a
final
Calendar argument and changes theCalendar.YEAR
field. - We create a new instance of
FinalArgs
and call itsrun()
method. ThemyFunc(final Calendar d)
method is called and the attibuteYEAR
offinal
Calendar is changed.
If we try to change the calendar though an error will occur, since it is final
and cannot be assigned to another value,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.Calendar; /** * Experiment with "final" args to functions (new in 1.1) */ public class FinalArgs { public static void main(String argv[]) { new FinalArgs().run(); } void run() { System.out.println("Hummm..."); myFunc(Calendar.getInstance()); System.out.println("Once upon a time..."); } void myFunc(final Calendar d) { // d = null; // this will not compile d.set(Calendar.YEAR, 1999); // this will compile, and changes the object } }
Output:
Hummm...
Once upon a time...
This was an example of how to use final arguments to a function in Java.