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?
The term Duck Typing is a lie.
Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.
Duck typing in Java. In OO programming, duck typing means an object is defined by what it can do, not by what it is. A statement calling a method on an object does not rely on the declared type of an object, only that the object must implement the method called.
Duck Typing is a term commonly related to dynamically typed programming languages and polymorphism. The idea behind this principle is that the code itself does not care about whether an object is a duck, but instead it does only care about whether it quacks.
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
See this blog post. It gives a very detailed account of how to use dynamic proxies to implement duck typing in Java.
In summary:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With