Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriden VS Redefinition

 
Abahmane mustafa
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Sujith Mahesh
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic