permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Methods" Watch "Static Methods" New topic

Static Methods

Savio Mascarenhas
Ranch Hand

Joined: Nov 29, 2000
Posts: 108
class BaseClass
static void sayHello()
public class SubClass extends BaseClass
static void sayHello()

public static void main(String args[])
BaseClass bc = new SubClass();
a)Does'nt compile as you cannot override static methods.
b)Compiles but fails at run-time.
c)prints output : "Base"
d)prints output : "Sub"
The answer is (c).
Using the subclass object,the overridden static method should be invoked .Why is the overridding method of the super class executed ?
Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
Static methods cannot be overridden.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
You can't override static methods, so you are hiding them. What happens when you declare your object, since it is declared as type base, and initialized as type sub, the comipler will assign any variables or static methods to it at compile time so it will be of type base, but non-static methods will be assigned at runtime, so they will be called from the sub class.
Add two more methods to your class that are not static and then have your object call them, and this time you will get the overridden version.
I agree. Here's the link:
subject: Static Methods
jQuery in Action, 3rd edition