Saturday, August 28, 2010

Polymorphism does NOT apply to static methods

Courtesy of Sun Web Learning Center


 4. class Slug {
 5.   static void crawl() { System.out.print("crawling "); }
 6. }
 7. public class BananaSlug extends Slug {
 8.   public static void main(String[] args) {
 9.     Slug[] sa = { new Slug(), new BananaSlug() };
10.     for(Slug s: sa)
11.       crawl();
12.   }
13.   static void crawl() { System.out.print("shuffling "); }
14. }
What is the result?


A crawling crawling
B crawling shuffling
C shuffling shuffling
D Compilation fails
E An exception is thrown at runtime.

C is correct. Polymorphism does NOT apply to static methods.

No comments:

Post a Comment