gm****@cs.bgu.ac.il (Mayer Goldberg) wrote in message news:<19**************************@posting.google. com>...
[snipped...]
But the language won't let me do this. It requires me to implement a
method with the signature foo(InterA x). The problem is that it
doesn't let me specify a different behaviour for foo() based on the
types that implement InterA. So it seems that I lose polymorphism
here.
You don't loose polymorphism, because strictly speaking that isn't
what polymorphism is about. One way to think about polymorphism is
as a way if defining different behaviours, accessible through a
standard interface - in the case of Java interfaces, the interface
defines *what* will be implemented, and the concrete classes which
use that interface defines *how* it will be implemented. (A simpl-
istic view, yes - but one which will do for the purposes of answering
your question.)
You want overloaded copies of the foo() method because you want to
have different behaviour depending upon what type of class gets
passed in - but these differences in behaviour should be encapsulated
inside each implementing class, not on the outside in code which
works with the class.
If we adopted your scheme we would loose 'scalability', because the
'accepting' method would have to have overloaded versions for every
implementation of an interface or subclass. Example: LayoutManager(2)
is an interface in AWT/Swing, which allows a class to be associated
with a container for the purposes of child layout. There are many
different types of LayoutManager - imagine if the Container class had
to have overloaded methods for every single one? Worse still - how
could we ever create our own layout manager, without modifying the
source code for Container, adding a method to accept it?
It shouldn't be difficult for a compiler to make sure that D
failthfully implements Inter by implemeing the methods, subclasses,
and subinterfaces specified in Inter for any class that implements
Inter. Therefore I can't understand why the language should place this
restriction.
As explained in the layout manager example above, the beauty of poly-
morphism is that we can collapse many different types of functionality
down to just one type, via means of a recognised signature/interface.
The reason AWT containers can accept any type of layout manager, and
indeed any type of component as a child, is because they adhere to
polymorphism: the differences between implementations are entirely
encapsulated inside each implementation, and no implementation-specific
code exists outside.
If you really have to have code 'outside' which treats different
implementations apart, you should either use 'instanceof', or define
overloaded methods which explicitly accept instances of individual
implementing classes (but then you loose the magic of polymorphism,
which is the ability to substitute any given implementation, providing
it adheres to the given interface/sig.)
-FISH- ><>