Recipe 8.13. Calling a Superclass's MethodProblemWhen overriding a class's method in a subclass, you want to extend or decorate the behavior of the SolutionUse the super keyword to call the superclass implementation of the current method. When you call super with no arguments, the arguments to your method are passed to the superclass method exactly as they were recieved by the subclass. Here's a Recipe class that defines (among other things) a cook method.
Here's a subclass of Recipe that tacks some extra behavior onto the recipe. It passes all of its arguments directly into super:
A subclass implementation can also choose to pass arguments into super. This way, a subclass can accept different arguments from its superclass implementation:
DiscussionYou can call super at any time in the body of a methodbefore, during, or after Often you want to create a subclass method that exposes exactly the same interface as its parent. You can use the *args constructor to make the subclass method accept any arguments at all, then call super with no arguments to pass all those arguments (as well as any attached code block) into the superclass implementation. Let the superclass deal with any problems with the arguments. The
If the subclass method takes arguments but the superclass method takes none, be sure to invoke super with an empty pair of parentheses. Usually you don't have to do this in Ruby, but super is not a real method call. If you invoke super without parentheses, it will pass all the subclass arguments into the superclass implementation, which won't be able to handle them. In the example below,
Invoking super works for class
|
Thursday, October 22, 2009
Recipe 8.13. Calling a Superclass's Method
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment