jeudi 23 avril 2020

In Java Passing final modifier in Method Parameter is of still no use [duplicate]

APPROACH 1: Without final keyword in method Parameter

void meth(Employee emp){
    emp.setName("some other name"); //WHATS WRONG IF WE DIRECTLY USE
}

APPROACH 2: Using final keyword in method Parameter

void meth(final Employee emp){
    Employee emp2 = emp; //IS THIS REALLY NOT UNNECESSARY?
    String name = emp2.setName("some other name"); 
}

APPROACH 3: Using final keyword in method Parameter

void meth(final Employee emp){
    emp.setName("some other name"); // I CAN STILL DO THIS, EVEN FINAL USED IN PARAMETER
}

In above snippets, one is using final keyword in Method Parameter and other is not. I knew that final keyword would be used, so that the object cannot be reassigned.

In case of APPROACH3, I can still able to do emp.setName("some other name");, then whats the point whether using final keyword for Method parameter, this doesn't make sense at all. I can change the state of an final Object, right? So, whats the benefit we getting there passing final modified in parameter..

Does APPROACH2 correct? especially Employee emp2 = emp; ??

Aucun commentaire:

Enregistrer un commentaire