*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static method" Watch "static method" New topic
Author

static method

Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
Posts: 39
the q. is from KATHY SIERRA book pg. no.147


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

class Dog extends Animal{
Static void doStuff(){
System.out.println("d ");
}
}
public static void main(String[] args){
Animal[] a={new Animal(),new Dog(),new Anmal()};
for(int x=0;x<a.length;i++){
a[x].doStuff();
}
}

OUTPUT:
a a a

in this question they specified the reason that Static method cant be overridden but can be redefine. So thats ok but why the OUTPUT is "a a a"


SCJP 1.5
Ganeshkumar cheekati
Ranch Hand

Joined: Oct 13, 2008
Posts: 362
here the type of the reference variable is Animal so it executes method in animal class only.
because static methods belongs to class only.


SCJP5 and SCWCD1.5
Think Twice Act Wise...
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

the call to static method depends on the type of the reference used to call them. This is because the compiler replaces the name of the reference used to call them with the type of the reference

eg

Animal obj = new Dog();
obj.staticMethod();

will become this after compilation

Animal obj = new Dog();
Animal.staticMethod();


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static method