Search code examples
javac++mutators

Using the final modifier with mutator methods


In C++ you could write

Int getX() const { return x; }

Is there an equivalent method structure in Java using final?

What about passing const/ final modified arguments to methods?

Like this C++ code

void printX(const int x); 

Solution

  • For the C++ example:

    void printX(const int x);
    

    you can use final modifier in method parameters to indicate the parameter can't be modified inside the method:

    void printX(final int x) {
        System.out.println(x);
        x++; //compiler error since `x` is marked as final
    }
    

    Note that using final modifier for object reference variables just means that the reference can't be modified, but its inner contents still can:

    class Foo {
        int x = 0;
    }
    class Bar {
        changeFoo(final Foo foo) {
            foo.x = foo.x + 1; //allowed even if `foo` is marked as final
            foo = new Foo(); //compiler error...
        }
    }
    

    From SJuan76 comment for this code

    Int getX() const { return x; }
    

    it tells that the class state is not modified when this method is called.

    There's no way in Java to mark a method like this.