• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method

 
Chetan Dodiya
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here the type of the reference variable is Animal so it executes method in animal class only.
because static methods belongs to class only.
 
Ankit Garg
Sheriff
Posts: 9497
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic