my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriden VS Redefinition Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriden VS Redefinition" Watch "Overriden VS Redefinition" New topic
Author

Overriden VS Redefinition

Abahmane mustafa
Greenhorn

Joined: Aug 22, 2007
Posts: 7
Hello all,

In page 147 of the book we can see :
****************
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
}
}
*******************
Running this code produces the output:
a a a

***********

I can't understand the difference between an ovverdie an redefinition in this case. For me it's clearly an override..but that is not legal for a static methode..
So is that piece of code legal or not?
How did you understood that ?


Preparing for SCJP 5.0
srinivas sridaragaddi
Ranch Hand

Joined: Jul 24, 2007
Posts: 225
Hi Mustafa,

Their is a rule called "Static methods cannot be overridden"

so in this case its exactly the same. Remember that in case of
Animal a=new Dog(); this condition is true. In other case
such as you create a object for the class and try to access the method it works fine.

What i exactly mean by that is


Animal ob=new Animal()
Dog ob1=new Dog()

ob.dostuff();//Animal dostuff is called
ob1.dostuff();//dog dostuff is called

here as we are using the exact reference the dostuff()corresponding class is called.

So finally as static generally applies for a particular class "Static methods cannot be overridden".And hence it cannot be called as overriding its redefinition of method.


Hope this helps you...
[ September 28, 2007: Message edited by: srinivas sridaragaddi ]

SCJP 5.0<br /> <br />"Skills are started with learning and mastered with improvement. Nothing is hereditary except death" BUDDHA...
Sujith Mahesh
Greenhorn

Joined: Jul 11, 2007
Posts: 6
doStuff() in animal class and doStuff() in Dog class are two different static methods. These two are different methods having same name.
And as they are static methods you need class name to access those methods.

In your code, you are using 'a[x].doStuff();' where 'a' represents Animal array. So always doStuff() of Animal class is called.

Hence its called Redefining and Not Overridding.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriden VS Redefinition