by Joker_vD · 2y ago · 0 comments
public interface ISwim { void Swim(); }
public interface IQuack { void Quack(); }
public interface IDuck extends ISwim, IQuack { }
public class Mallard implements IDuck {
public void Swim() { System.out.println("mallard swimming"); }
public void Quack() { System.out.println("mallard quacking"); }
}
public class Dog implements ISwim {
public void Swim() { System.out.println("dog swimming"); }
public void Bark() { System.out.println("dog barking"); }
}
public static void quack(Object... ducks) {
for (Object duck: ducks) {
((ISwim)duck).Swim();
((IQuack)duck).Quack();
}
}
public static void main() {
quack(new Mallard(), new Dog());
}
in Java? You can do this in Java, you know, casting down to an interface; the same goes for C#. Do those languages now have duck typing, just because in them you can up-cast anything to Object, and then try to down-cast to any other type, be it an interface or a class?Maybe. I don't have a language reference handy. Does runtime type checking take place with that code?
My impression, based on the way you said it (and my vague memories of using Java once upon a time), is no. On that assumption, where would you find the duck type? The significance of both structural typing and duck typing is that type checking occurs. As before, the difference is when the check takes place – be it at compile time or at runtime.
Perhaps you could update that code to demonstrate how you would bypass calling objects which, when type checked, show to not quack like a duck like as is shown in the Go examples?
And no, the structural/duck typing is not about when the type checking happens. It's about not having to write "implements IDuck" right in the class declaration for the down-cast to succeed.
That doesn't make sense. Not having to write "implements IDuck" is true of both structural typing and duck typing. That logically cannot be what makes them different.
My original point was that TFA doesn't really feature duck/structural typing; the example program just shows dynamic upcasting/downcasting, which has been a staple of OOP since forever, and has no relation to duck/structural typing.
In practice, the use of dynamic is highly discouraged as well as anything that could lead to type confusion i.e. currently discussed Go's duck typing it calls structural (runtime vs static is impl. detail).
Instead, you are expected to simply do 'lessSpecific is IMoreSpecific ms`, works particularly well with pattern matching on switches for functional style.