Skip to content

Comment on Hacking a Google Interview - MIT's guide to Google interviewsparent

Comments

Any definition of polymorphism should at least mention something about the method that is invoked depends on runtime data, and is not resolved (or known) at compile time.

I'm not sure that's always true. Or at the very least seems language dependent.

Yeah, Java doesn't do multimethods (i.e., method dispatch based on runtime argument types).

If Class X has two methods:

  void foo(Object i);
  void foo(Integer i);
then:
  Object test = new Integer(4);
  X x = new X();
  x.foo(test);
will invoke 'void foo(Object o);' based on the compile time type of test.

Java does do dispatch based on the runtime type of X - but it is quite limiting once you are used to having proper multiple dispatch at your disposal.

(caveat: not in front of a javac - this is from memory).

You're right. It calls 'void foo(Object o);'

    import junit.framework.TestCase;
    
    public class TestMultimethods extends TestCase {
        public void test() {
          Object test = new Integer(4);                                        
          X x = new X();                                                       
          assertEquals(x.foo(test), "foo(Object)");
        }
    }
    
    class X {
        String foo(Object i) { return "foo(Object)"; }
        String foo(Integer i) { return "foo(Integer)"; }
    }
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.