• Post Reply Bookmark Topic Watch Topic
  • New Topic

Duck typing  RSS feed

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

Consider the following pseudo-code for a duck typed language:

function calculate(a, b, c) => return (a+b)*c

example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)

print to_string example1
print to_string example2
print to_string example3

function calculate(a, b, c) => return (a+b)*c

example1 = calculate (1, 2, 3)
example2 = calculate ([1, 2, 3], [4, 5, 6], 2)
example3 = calculate ('apples ', 'and oranges, ', 3)

print to_string example1
print to_string example2
print to_string example3

Interfaces can provide some of the benefits of duck typing but duck typing is distinct in that no explicit interface is defined. For example, if a third party Java library implements a class you are not allowed to modify, you cannot use an instance of the class in place of an interface you have defined yourself, whereas duck typing would allow this. Again, all of an interface must be satisfied for compatibility.

Sourced from here.

Can you clarify with an example and related articles on how Java deals with generic programming?
Can you provide an example of an algorithm (preferably simple) or generic programming you might have come across or written in Java?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is a statically, strongly typed programming language; the types of variables and expressions must be known at compile time, unlike dynamically typed languages like Ruby or Python where variables don't have a fixed type at compile time.

Duck typing is a feature of dynamically typed programming languages, Java does not support it because it is statically typed.

Duck typing doesn't have a lot to do with generic programming.

If you want to learn about generics in Java, then have a look at this tutorial chapter: Lesson: Generics.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!