Recipe 7.5. Preventing Changes to Classes and Methods7.5.1. ProblemYou 7.5.2. SolutionLabel the particular methods or class as final public function connect($server, $username, $password) { And: final class MySQL { 7.5.3. DiscussionInheritance is normally a good thing, but it can make sense to restrict it. The best reason to declare a method final is that a real danger could arise if someone overrides it. For example, data corruption, a race condition, or a potential crash or deadlock from forgetting (or forgetting to release) a lock or a Another common reason to declare a method final is that the method is "perfect." When you believe there's no way to update the method to make it better, declare it using the final keyword. This prevents subclasses from ruining it by reimplementing the method in an inferior manner. However, think hard before you choose final in this case. It's impossible to come up with all the reasons someone may need to override a method. If you're distributing a third-party library (such as a PEAR package), you will cause a real headache if you incorrectly mark a method as final. Make a method final by placing the final keyword at the beginning of the method declaration, as shown in Example 7-12. Defining a final method
This prevents someone from subclassing the class and creating a different To prevent subclassing of an entire class, don't mark each method final. Instead, make a final class as shown in Example 7-13. Defining a final class
A final class cannot be subclassed. This differs from a class in which every method is final because that class can be extended and provided with additional methods, even if you cannot alter any of the preexisting methods. |
Monday, January 25, 2010
Recipe 7.5. Preventing Changes to Classes and Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment