• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Static Methods

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static methods cannot be overridden.
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic