Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

override and redifinition?

 
ge weipeng
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, i just have a problem with the following code:
class Animal{
static void doStuff(){
System.out.print("a");
}
}
class Dog extends Animal{
static void doStuff(){
System.out.print("b");
}
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();
}
}
They say that the method doStuff() in class Dog is not an override,but a redifinition.Why?What's the difference between them?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Polymorphism (i.e. overriding methods) only works for non-static methods. Therefore the doStuff() in class dog is just shadowing the one from the base class because of the name clash but besides the two methods aren't related like overridden methods.

Have a look at this for an explanation of polymorphism ;-)

Marco
 
ge weipeng
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much!
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Campbell Ritchie
Sheriff
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic