3.5 The Three Pillars of Object-Oriented ProgrammingObject-oriented programming is built on three sturdy pillars: encapsulation , specialization , and polymorphism . Each class should be fully encapsulated, that is, it should fully define the state and responsibilities of that type. For example, if you create an Employee object, that Employee object should fully define all there is to know, from the perspective of your program, about each Employee. You do not, typically, want to have one class that defines the Employee's work information and a second, unrelated class that defines the Employee's contact information. Instead, you want to encapsulate all this information inside the Employee class, perhaps by aggregating the contact information as a member of the Employee class.
Specialization allows you to establish hierarchical relationships among your classes. For example, you can define a Manager to be a specialized type of an Employee and an Employee to be a specialized type of Person. This allows you to leverage the state and
Polymorphism allows you to treat a
|
3.6 Encapsulation
The first
A class that provides a method that other classes can use is called a server . A class that uses that method is called a client . Encapsulation allows you to change the details of how a server does its work without breaking anything in the implementation of the client. This is accomplished by drawing a bright and shining line between the public interface of a class and its private implementation . The public interface is a contract issued by your class that says, "I promise to be able to do this work." Specifically, you'll see that a public interface says, "call this method, with these parameters, and I'll do this work, and return this value." A client can rely on a public interface not to change. If the public interface does change, then the client must be recompiled and perhaps redesigned.
On the other hand, the private implementation is, as its
For example, you might have a public method that promises as
|