Sorry, quick question here, just found something in my notes I don't understand in relation to making a method final. My notes claim you should make a method final for this reason :
Makes it impossible to enforce invariants.
A String should behave as a String.
I don't really understand what is meant by this. Can someone please break it down for me ? Thanks a lot.
Those notes don't make much sense - I think impossible should be 'possible'. The idea is that if you don't want subclasses to change the behavior of a method, you can mark the method as final and it will not be able to be overridden. This gives finer grained control than marking the entire class as final.
Prints "Not A: A"
If the super class method "print(" were final this type of bug could not happen.
Via final you can enforce this method remaining unchanged so that A can always be happy printing "A"
I would guess that should have said "Make it possible to enforce invariants". Basically, if someone can override a method, then they can change behaviors affecting your class's invariants.
Your notes might make more sense if they read:
In other words, finalizing a method ensures that it will return the value that you mean it to, instead of returning an overridden value that someone else mistakenly thought it should be.
A
String
is unmodifiable upon its creation. What that means is that all its internal fields are declared final, and it provide no method to update its internal contents. Therefore, when you declare a string as "i am string", you know that the string you declared will hold that value until the end of the time.A method should be declared final when you don't want the method to be overridden by a class that extends yours. A class that has only final methods can still be mutable if any of these methods change the variables inside the class.
I like using unmodifiable classes, it does help me to know the state of my program at any time and in a way it prevent bugs that would be hard to catch.
Basically if you make a method final, then you can't override that method in a subclass.
If the behaviour of your application relies on a certain method behaving exactly in a certain way and you don't want other developers to come along and change this behaviour, then you can use the 'final' keyword.