2
class T {}

interface Interface{
    void method(final T t);
}

class FirstClass implements Interface{

    public void method(T t){
         //valid
    }

    public void method2(final T t){

    }
}

class SecondClass extends FirstClass {
    public void method2(T t){
        //valid
    }
}

In the above code, why it is not considering the final qualifier while overriding a method?

My understanding of final qualifier in method signature is, the method will not allow to change the reference. But I don't understand what is the use of it?

Lets say I'm using 3rd party jar, and I'm concern about that 3rd party jar should not change my object while it processing, the code should be like this,

3rdPartyClass.doProcess((final) myObject);

class 3rPartyClss {
  public void doProcess(SomeClass myObject){}
}

but why its like

3rdPartyClass.doProcess(myObject);

class 3rPartyClss {
  public void doProcess(final SomeClass myObject){}
}

If the 3rd party knows he is not going to change the object reference inside the method, then what is the use of having final in signature? In overriding method also it will not consider the final qualifier. Then what is the real use of it?

I found similar question like this here, but want more clarification on this

Community
  • 1
  • 1
Nageswaran
  • 7,481
  • 14
  • 55
  • 74

1 Answers1

4

In the above code, why it is not considering the final qualifier while overriding a method?

Because it's an implementation detail. It's completely irrelevant to callers. All it means is that within the method, the code can't assign a new value to that parameter. Even if it could, the caller wouldn't see that new value. (That also means it can be used within an anonymous method within the method as well, but that's a sort of side-effect.)

The only aspects of a method which are important for overloading and overriding are the ones which matter to the caller - parameter types, accessibility, and the method name. (The return type is important for overriding but not overloading; whether a method is static or not affects different things in different ways.) Whether or not the parameter is final is as irrelevant as whether the method is synchronized.

Any method with a final parameter like this:

public void foo(final String x) {
    ...
}

can simply be rewritten as:

public void foo(String x) {
    final String y = x;
    // Code using y instead of x
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194