Geeks With Blogs
Daniel Forhan Computer Science Teacher and Java Programmer

Today four of my students are competing in a programming contest at Fitchburg State College (MA). Since I cannot interact with them during the competition I have had a little time to catch up on some of the blogs/newsletters that I enjoy reading (and update my blog). One thing I came across this morning was a neat Java puzzle from one of my favorite Java sources, the The Java Specialists' Newsletter . This probably falls under the expert category. The result is a little surpising, and interesting to say the least. Here it is. See if you can predict the output. (assume each class is in a separate file). Have fun.

package com.cretesoft.tjsn.issue117;


public class Greeter {
  public void hello() {
    System.out.println("Hello from Greeter");
  }
}
  
package com.cretesoft.tjsn.issue117;

public class Exec {
  public static void run(Greeter target) {
    System.out.println();

    System.out.print("method call> ");
    target.hello();

    System.out.print("base class > ");
    run(target, Greeter.class, "hello");

    System.out.print("obj class  > ");
    run(target, target.getClass(), "hello");
  }

  // this calls the method using reflection

  static void run(Greeter target, Class cls, String method) {
    try {
      cls.getMethod(method, null).invoke(target, null);
    } catch (Exception x) {
      System.out.println(x);
    }
  }
}
  
package com.cretesoft.tjsn.issue117;


public class InsideJob {
  public static void run() {
    Exec.run(new Greeter() {
      public void hello() {
        System.out.println("Hello from InsideJob");
      }
    });
  }
}
  
import com.cretesoft.tjsn.issue117.*;

public class Main {
  public static void main(String[] args) {
    InsideJob.run();
    Exec.run(new Greeter() {
      public void hello() {
        System.out.println("Hello from Main");
      }
    });
  }
}
  

This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa). Please contact Maximum Solutions for more information.

Try on paper before you compile. Did you get it?

More detailed discussion can be found here.

 

Posted on Friday, December 2, 2005 7:42 AM | Back to top

Copyright © Daniel Forhan | Powered by: GeeksWithBlogs.net