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.
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


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Methods" Watch "Static Methods" New topic
Author

Static Methods

Savio Mascarenhas
Ranch Hand

Joined: Nov 29, 2000
Posts: 108
Q.36.
class BaseClass
{
static void sayHello()
{
System.out.println("Base");
}
}
public class SubClass extends BaseClass
{
static void sayHello()
{
System.out.println("Sub");
}

public static void main(String args[])
{
BaseClass bc = new SubClass();
bc.sayHello();
}
}
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.
Bill
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Static Methods