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 method func().
  • We have also created a class FinalArguments, that has a method with(final Giz g) and another method without(Giz g). The first method uses a final Giz parameter. The second method gets a Giz parameter that is not final this time, sets it to a new instance of Giz and calls its func() method.
  • FinalArguments also has method g(final int i) that increaments an i by one and returns it.
  • Since with(final Giz g) and g(final int i) methods have final arguments they cannot change them. For example we cannot set a different value to final int i in g(final int i) method or set a new instance of Giz to agrument Giz g in with(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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button