7.14. Class Abstraction and Encapsulation

 
[Page 239 ( continued )]

In Chapter 5, " Methods ," you learned about method abstraction and used it in program development. Java provides many levels of abstraction. Class abstraction is the separation of class implementation from the use of a class. The creator of a class provides a description of the class and lets the user know how the class can be used. The collection of methods and fields that are accessible from outside the class, together with the description of how these members are expected to behave, serves as the class's contract . As shown in Figure 7.22, the user of the class does not need to know how the class is implemented. The details of implementation are encapsulated and hidden from the user. This is known as class encapsulation . For example, you can create a Circle object and find the area of the circle without knowing how the area is computed.

Figure 7.22. Class abstraction separates class implementation from the use of the class.

Class abstraction and encapsulation are two sides of the same coin. There are many real-life examples that illustrate the concept of class abstraction. Consider building a computer system, for instance. Your personal computer is made up of many components , such as a CPU, CD-ROM, floppy disk, motherboard, fan, and so on. Each component can be viewed as an object that has properties and methods. To get the components to work together, all you need to know is how each component is used and how it interacts with the others. You don't need to know how it works internally. The internal implementation is encapsulated and hidden from you. You can build a computer without knowing how a component is implemented.

The computer-system analogy precisely mirrors the object-oriented approach. Each component can be viewed as an object of the class for the component. For example, you might have a class that models all kinds of fans for use in a computer, with properties like fan size and speed, and methods like start, stop, and so on. A specific fan is an instance of this class with specific property values.

Consider getting a loan, for another example. A specific loan can be viewed as an object of a Loan class. Interest rate, loan amount, and loan period are its data properties, and computing monthly payment and total payment are its methods. When you buy a car, a loan object is created by instantiating the class with your loan interest rate, loan amount, and loan period. You can then use the methods to find the monthly payment and total payment of your loan. As a user of the Loan class, you don't need to know how these methods are implemented.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net