My question is: What does mean to override a method. Can someone show me an example of this. Thank you The rules for overriding can be summarized as follows: A private method may be overridden by a private, default, protected, or public method. A default method may be overridden by a default, protected, or public method. A protected method may be overridden by a protected or public method. A public method may only be overridden by a public method.
Method overriding deals with inheritence, where the parent and child class each have a function with the same name. Run this example to see what happens:
Actually, the last line in main() illustrates polymorphism, which is another topic closely related to method overriding. Before you run it, you should predict what you think the output will be. Then see if it is what you predicted. Standard Disclaimer: the above code has not been compiled or tested. I created it from memory and should work as is. However, no warranty is given, explicit or implied. Use at your own risk. HTH Layne [ March 26, 2003: Message edited by: Layne Lund ]
the parent and child class each have a function with the same name
This is also true of overloading, a totally different concept. So beware. To override:
the methods must have the same name
the methods must have the same return type
the methods must have the same number of parameters
the methods' parameters must correspond one-to-one regarding the type of the parameters
the overriding method's access modifier must be of equal or weaker strictness (as original post)
The overriding method can only throw a subset (or none) of the exceptions declared in the throws clause of the overridden method.
(I've probably forgotten something else too) A method having the same name but different parameter list (number of parameters, or type correspondence) is overloaded. Examples are to be found in the Programmer Certification Forum. [ March 27, 2003: Message edited by: Barry Gaunt ] [ March 27, 2003: Message edited by: Barry Gaunt ]
This is also true of overloading, a totally different concept. So beware.
Doh! Thank you for catching that. I meant to say "the parent and child class each have a function with the same signature," which is obviously very different. A methods signature is exactly what Barry described: the name and parameters. Of course, it doesn't seem this is completely accurate, either. I didn't know that you have to have the exact same return type to override a method as well. I guess this makes sense because the compiler will be thoroughly confused if the parameter list and name are the same, but the return type is different. I should code up an example program to explore some of the issues involved here.