Daniel Forhan
Computer Science Teacher and Java Programmer

Java Puzzle

Friday, December 02, 2005 7:42 AM

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.

 


Feedback

# re: Java Puzzle

How did the students do in the competition? 12/13/2005 10:40 AM | Pat Phillips

# re: Java Puzzle

Hi Pat,

The kids did well, there were some technical issues with the automated scoring, but they recovered ok from that. I believe them came in 5th place out of a field of about 14 teams. Not bad considering it was the first time any of these kids have been to such an event.

Dan
12/14/2005 4:37 AM | Daniel Forhan

Post a comment