• 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:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

a question

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Animal
{
static void doStuff()
{
System.out.print("a ");
}
}

class Dog extends Animal
{
static void doStuff() //redefinition,not overridden

{
System.out.println("Dog");
}
public static void main(String[] args)
{
Animal[] a={new Animal(),new Dog(),new Animal()};

for(int x=0;x<a.length;x++)
{
a[x].doStuff();
}
}
}

well the answer i got is "a a a" when i expected " a Dog a" where have i gone wrong

a[0].doStuff() becomes Animal.doStuff() which becomes 'a'
a[1].doStuff() becomes dog.doStuff() which becomes 'Dog'
a[2].doStuff() becomes Animal.doStuff() which becomes 'a'

this is my interpretation but evidently i have gone wrong but where ?
 
Sheriff
Posts: 9709
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static methods are called on the type of the reference on which the method is called and not the type of the object stored in the reference stored in the object....

For eg.

this is because after compilation the main method would look as
Base obj = new Derived();
Base.hello(); //displays Hello!

As you can see that the compiler replaces the name of the object with the name of the type of the reference with which the method was called. This happens only in case of static methods....
 
Ranch Hand
Posts: 54
Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Basically we can't override an static method. In this example it is hiding not overriding.I you override a method you will get the benefits of run-time polymorphism,if you hide it you wont.
Since polymorphism does not work you will get a a a instead of a Dog a .
 
sasank manohar
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you guys !!
[ August 12, 2008: Message edited by: sri dev ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic