Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Methods

 
Savio Mascarenhas
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods cannot be overridden.
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic