Is it a polymophism?
Interface ABCListener
{
public void test();
};
Class ABC
{
ABCListener listener;
public void SetListener(ABCListener listener)
{ this.listener = listener; }
public void run()
{this.listener.test();}
};
Class MainClass implement ABCListener
{
ABC abc;
public void test() {...};
};
From the above example, I don't know why when I call the the run method of ABC object and the listener can auto detect the test function implemented by MainClass?
If so, there has more than one MainClass that implement the test() method, what is the result?
[670 byte] By [
GDMichaela] at [2007-11-27 1:21:28]

> Lose those extra semicolons after }'s, though. While not Java-ish, rather C++-ish, semicolons after complete classes are allowed by the Java-syntax for the sake of C++-people.
> Interface ABCListener
> {
> public void test();
> };
>
> Class ABC
> {
> ABCListener listener;
> public void SetListener(ABCListener listener)
> { this.listener = listener; }
>
> public void run()
> {this.listener.test();}
>
> };
>
> Class MainClass implement ABCListener
> {
> ABC abc;
>
> public void test() {...};
> };
>
>
>
> From the above example, I don't know why when I call
> the the run method of ABC object and the listener can
> auto detect the test function implemented by
> MainClass?
> If so, there has more than one MainClass that
> implement the test() method, what is the result?
This is exactly what polymorphism is all about. Java allows classes to redefine methods inherited from their superclass(es). The decision of which version of the method gets called is made a runtime, and is dependent on the runtime type of the object.
So, to clear up what happens when more than one MainClass implements the test() method, well, it would probably be an error to define more than one class called "MainClass" ;-) . Seriously, though, if you had classes ABCImplementation1 and ABCImplemenation2 which both implement ABCListener, then the method executed would depend on whether the actual listener was an instance of ABCImplementation1 or ABCImplementation2.
- Adam