Win a copy of Head First Android this week in the Android forum!
  • 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 Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Redefining a static method

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

My first post, the first of many.

P 147 has an example of referencing as follows

class Animal {
static void doStuff() {
System.out.print("a ");
}
}

class Dog extends Animal {
static void dostuff() { // it's a redefinition,
// not an override
System.out.print("d ");
}

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(); // invoke the static method
}
}

which results in

a a a

I don't understand why there isn't a b in there, I'm guessing it's because the reference type is Animal?

Then I tried this, a set of dogs calling a static method

Set<Dog> ds = new HashSet<Dog>();

ds.add(new Dog());
ds.add(new Dog());
ds.add(new Dog());

for (Dog oneDS : ds)
{
oneDS.doStuff();
}

and still get

a a a

Please explain.
 
Wyn Riley
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, that should have read

P 147 has an example of redefining a static method as follows
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Wyn Riley:
...

and still get

a a a

Please explain.


Welcome to JavaRanch!

Remember, Java is case sensitive. If you look carefully at your Dog class, you will see that the static method is dostuff -- not doStuff. So you are still calling the inherited static method in Animal.

(Tip: Please use Code Tags to keep your indentation intact. )
[ July 05, 2007: Message edited by: marc weber ]
 
Wyn Riley
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Marc

I'll try and get past the beginner's mistakes as quickly as possible!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic