13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.4 Encapsulati<strong>on</strong>, Inheritance, and Polymorphism913.4.3 PolymorphismPolymorphism (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 thatJava does this via the extends and implements keywords. You can define aninterface and then define two classes that both implement this interface.Remember our Sample class (Example 3.26). We’ll now define anotherclass, Employee, which also implements the Identifiable interface(Example 3.27).Example 3.27 The Employee classclassEmployeeextends Pers<strong>on</strong>implements Identifiable{private int empl_id;}public int getID(){return empl_id;}Notice that the same method, getID(), is implemented in the Employeeclass, but that the field from which it gets the ID value is a different field. That’simplementati<strong>on</strong>-specific—the interface defines <strong>on</strong>ly the methods that can becalled but not their internal implementati<strong>on</strong>. The Employee class not <strong>on</strong>lyimplements Identifiable, but it also extends the Pers<strong>on</strong> class, so we bettershow you what our example Pers<strong>on</strong> class looks like (Example 3.28).To make a really useful Pers<strong>on</strong> class would take a lot more code than weneed for our example. The important part for our example is <strong>on</strong>ly that it isquite different from the Sample class we saw earlier.Example 3.29 dem<strong>on</strong>strates the use of polymorphism. We <strong>on</strong>ly show somesmall relevant snippets of code; there would be a lot more code for this to becomean entire, complete example. D<strong>on</strong>’t be distracted by the c<strong>on</strong>structors; wemade up some new <strong>on</strong>es just for this example, that aren’t in the class definiti<strong>on</strong>sabove. Can you see where the polymorphism is at work?

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!