
: c07:music:Music.java // Inheritance & upcasting. In the following example, Wind is a type of Instrument, therefore Wind is inherited from Instrument: You cant make additional objects because the constructor is private.

This is an enumeration class, which has a fixed number of constant objects to choose from. : c07:music:Note.java // Notes to play on musical instruments. Since several examples play Notes, we should create the Note class separately, in a package: You also saw a problem arise, which is embodied in the following example about musical instruments. Taking an object reference and treating it as a reference to its base type is called upcasting because of the way inheritance trees are drawn with the base class at the top. In Chapter 6 you saw how an object can be used as its own type or as an object of its base type. In this chapter, youll learn about polymorphism (also called dynamic binding or late binding or run-time binding) starting from the basics, with simple examples that strip away everything but the polymorphic behavior of the program. This distinction is expressed through differences in behavior of the methods that you can call through the base class. The polymorphic method call allows one type to express its distinction from another, similar type, as long as theyre both derived from the same base type.
#Java chapter6 methods a deeper look solutions code#
This ability is critical because it allows many types (derived from the same base type) to be treated as if they were one type, and a single piece of code to work on all those different types equally. In the last chapter, you saw how inheritance allows the treatment of an object as its own type or its base type. Chapter 4: Java Collections Chapter 5: Java Multithreading Chapter 6: Java Executor Framework Chapter 7: Java Concurrency util Chapter 8: Java Serialization. But polymorphism deals with decoupling in terms of types. This sort of mechanical organization makes ready sense to someone with a procedural programming background. Implementation hiding separates the interface from the implementation by making the details private.

FeedbackĮncapsulation creates new data types by combining characteristics and behaviors. Polymorphism allows improved code organization and readability as well as the creation of extensible programs that can be grown not only during the original creation of the project, but also when new features are desired. It provides another dimension of separation of interface from implementation, to decouple what from how. Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance.
