This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Is this true: "static methods can be overridden by static methods only".( from java_cert exam) The answer is false. can someone tell me why? can static method be overriden? If yes, what are ways of overriding a static method?
Originally posted by derek_ho: Is this true: "static methods can be overridden by static methods only".( from java_cert exam) The answer is false. can someone tell me why? can static method be overriden? If yes, what are ways of overriding a static method?
No, it is not true. Static methods cannot be overridden, rather, they can be hidden. This program shows the difference between method hiding and overridding.
As you can see, line 1 works as expected. You are making a method call on an SuperClass object reference variable, but because the actual instance is of type SubClass, the overridden method gets called. In line 2, when we attempt to do the same thing with a static method, we see that the same rules do not apply. The static method that gets invoked is the one that is a member of the reference variable's class, NOT the one that is a member of the actual object instance! This shows that there is a very real, tangible, important distinction between static and instance methods, and between hiding and overridding. It also shows why it is Bad Form to refer to a static member by an reference variable; you should always use the class name to access a static member. In the above line 2, if you had written SubClass.staticPrintClassName(); SuperClass.staticPrintClassName(); it would be clear which method would be invoked.
Rob,Based on the code,how to invoke the method printClassName() of superClass?
help you means help me
Joined: Jan 07, 2002
Seany, there are only two ways. One, instantiate an object of type SuperClass and call that method. SuperClass sc = new SuperClass(); sc.printClassName(); Two, create a subclass of SuperClass. Subclasses can call super.printClassName() and access the overridden method.
Joined: Jan 08, 2002
Two, create a subclass of SuperClass. Subclasses can call super.printClassName() and access the overridden method
Rob, thank you. I know the first way you told. But as for the second,It's only be called in subclass? If out the subClass, can it?
Joined: Jan 07, 2002
No Seany. If you have an object instance of type SubClass, and you call printClassName()on that object, there is no way for you to invoke the SuperClass version. The only method available to you is the overridden version. Rob