What Could be the example scenarios to declare any class or any method as "final"? When do we need to do this?
Please give me some example to understand the practical use of "final"...
please elaborate your answer....
please guide me as I am a beginner in OOP
This is just an example to elaborate why methods/classes must be locked down sometimes from any further extensions to avoid surprises.
class Account {
public function debit(Amount $amount) {
if(($this->canDebit($amount)) {
$this->balance -= $amount;
}
}
final public function credit(Amount $amount) {
...
}
}
class CheckingAccount extends Account {
public function debit(Amount $amount) {
// we forgot to check if user canDebit()
$this->balance -= $amount;
}
}
This is just an example to illustrate why it's necessary to make methods and classes final. In fact, it is a very good practice to make all your methods and classes final unless you know you are going to extend them, and the subclasses may want (and will be allowed) to extend/override the base class.
Basically you declare any class final when you think it should not be extended any more or there is no need for either you or anyone else to extend that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With