|
February 14, 2001 Defining Duplicate Functions Tips: February 2001
Yehuda Shiran, Ph.D.
|
|
Sometimes you want to define a method in a superclass and then override it with a method in a subclass. For overriding to work correctly, both methods need to have the same name. But how do you define two distinct functions with the same name? If you define them as global variables, the last definition overrides the first one. The solution is to define each function inside its relevant class. When you do that, each function is associated with the right class, and there is no overriding of function definitions. Still, the subclass definition overrides the superclass one. The following code demonstrates this behavior. The class subClass() defines the method allBye() which prints an alert box that greets you from subClass(). The class superClass() defines the method allBye() as well, greeting you from superClass(). The subclass method overrides (by design) the superclass method. When clicking here, you'll get two alert boxes. The first one, alert(newClass.bye()), demonstrates that the definition of the allBye() method in subClass() was not overridden by the later definition inside superClass(). The second alert box, alert(newClass.hello()), demonstrates the inheritance of the hello() method by subClass(). here are the classes:
And the print function is:
People who read this tip also read these tips: Look for similar tips by subject: |