" A static method can only be overridden by a static method in the derived class " But why do many mock exams give the result "NO" for the question Can static methods be overridden [ August 26, 2005: Message edited by: sankar velamuri ]
If you consider overriding the simple replacement of a method in a child class it is easy to believe at static methods can be overriden. Indeed I have had many emails from people that include code that appears to illustrate how static methods can be overriden. However this does not take into account the more subtle aspect of overriding which is the runtime resolution of which version a method will be called. The following code appears to illustrate how static methods can be overriden.
If you compile and run this code you will find it outputs the text Cravengib.amethod, which appears to be a nice illustration of overriding.
However there is more to overriding than simple replacement of one method by another in a child class. There is also the issue of runtime resolution of methods based on the class type of the reference. and this can be illustrated by making the type of the reference (the part on the left hand side of the instance initialisation) to the type of the class that is being instantiated.
In the previous example, because the method called amethod is associated with the class, and not with any particular instance of the class it does not matter what the type of class being created it, just the type of the reference. Thus if you change the line before the callng of amethod to read
Base cg= new Cravengib()
You will find that when you run the program you get an output of
The reference cg is a reference (or pointer) of type Base to an instance in memory of the class Cravengib. When a call is made to a static method, the JVM does not check to see what the type is that is being pointed to it just calls the one instance of the method that is associated with the Base class. By contrast when a method is overriden the JVM checks the type of the class that is being pointed to by the reference and calls the method associated with that type.
To complete the illustration, if you change both versions of amethod to be non static, keep the creation of the class to
Base cg= new Cravengib()
compile and run the code, and you will find that amethod has been overriden and the output will be
Cravengib.amethod [ August 27, 2005: Message edited by: Marcus Green ]