javaduck-typing

What's an example of duck typing in Java?


I just recently heard of duck typing and I read the Wikipedia article about it, but I'm having a hard time translating the examples into Java, which would really help my understanding.

Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it?


Solution

  • Java is by design not fit for duck typing. The way you might choose to do it is reflection:

    public void doSomething(Object obj) throws Exception {
    
        obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
    }
    

    But I would advocate doing it in a dynamic language, such as Groovy, where it makes more sense:

    class Duck {
        quack() { println "I am a Duck" }
    }
    
    class Frog {
        quack() { println "I am a Frog" }
    }
    
    quackers = [ new Duck(), new Frog() ]
    for (q in quackers) {
        q.quack()
    }
    

    Reference