Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
Cuga Avatar asked Jul 03 '09 15:07

Cuga


People also ask

Is duck typing a form of touch typing?

The term Duck Typing is a lie.

What is use of duck typing?

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.

What is duck typing in Java?

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.

What is duck typing languages?

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.


2 Answers

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

like image 84
Robert Munteanu Avatar answered Sep 20 '22 18:09

Robert Munteanu


See this blog post. It gives a very detailed account of how to use dynamic proxies to implement duck typing in Java.

In summary:

  • create an interface that represents the methods you want to use via duck typing
  • create a dynamic proxy that uses this interface and an implementation object that invokes methods of the interface on the underlying object by reflection (assuming the signatures match)
like image 42
Dean Povey Avatar answered Sep 21 '22 18:09

Dean Povey