Java Reference
In-Depth Information
3.4.3
Polymorphism (from the Greek poly meaning “many” and morph meaning
“shape”) refers to the language's ability to deal with objects of many different
“shapes,” that is, classes, as if they were all the same. We have already seen that
Java does this via the extends and implements keywords. You can define an
interface and then define two classes that both implement this interface.
Remember our Sample class (Example 3.26). We'll now define another
class, Employee , which also implements the Identifiable interface
(Example 3.27).
Polymorphism
Example 3.27 The Employee class
class
Employee
extends Person
implements Identifiable
{
private int empl_id;
public int getID()
{
return empl_id;
}
}
Notice that the same method, getID() , is implemented in the Employee
class, but that the field from which it gets the ID value is a different field. That's
implementation-specific—the interface defines only the methods that can be
called but not their internal implementation. The Employee class not only
implements Identifiable , but it also extends the Person class, so we better
show you what our example Person class looks like (Example 3.28).
To make a really useful Person class would take a lot more code than we
need for our example. The important part for our example is only that it is
quite different from the Sample class we saw earlier.
Example 3.29 demonstrates the use of polymorphism. We only show some
small relevant snippets of code; there would be a lot more code for this to be-
come an entire, complete example. Don't be distracted by the constructors; we
made up some new ones just for this example, that aren't in the class definitions
above. Can you see where the polymorphism is at work?
Search WWH ::




Custom Search