Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Could be the example scenarios to declare any class or any method as "final"?

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

like image 912
OM The Eternity Avatar asked Feb 27 '23 03:02

OM The Eternity


2 Answers

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.

like image 183
Anurag Avatar answered Apr 05 '23 22:04

Anurag


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.

like image 33
Sarfraz Avatar answered Apr 06 '23 00:04

Sarfraz