Encapsulation vs. Inheritance

To allow subclasses to access the attributes of the parent, language designers have included the access modifier protected. There are actually two types of protected access, which I will explain in detail later. Right now, change the color access modifier to protected, as seen in Listing 8.

Listing 9

The problem is that this now works (see Figure 7). In short, the application (class Packaging) can directly access Dog's color attribute. Based on the rule of encapsulation, this is unacceptable. It appears that you have fixed the inheritance issue, but now you have broken encapsulation. What can you do?

Figure 7

You clearly have a dilemma. It appears that you have to make a decision as to whether to enforce inheritance or encapsulation. This example clearly shows the problem that inheritance poses to encapsulation. It is very helpful for a developer to fully understand the subtleties involved with the inner workings of various object-oriented constructs. By realizing what the issues are in this example, you can more fully grasp what inheritance and encapsulation are and how to make your designs more robust.

Conclusion

Many of the decisions that you need to make will be dictated to you by the implementation of the language that you choose. In Java, you can use the protected access modifier. In fact, there are two types of protected access modifiers that you need to understand before you can make the best possible design decision. You also need to take advantage of the Java packaging rules. This is why the application was named Packagingin anticipation of next month's column. As you may have already guessed, next month's column will cover the use of the protected access modifiers along with the use of packages.

About the Author

Matt Weisfeld is a faculty member at Cuyahoga Community College (Tri-C) in Cleveland, Ohio. Matt is a member of the Information Technology department, teaching programming languages such as C++, Java, and C# .NET as well as various web technologies. Prior to joining Tri-C, Matt spent 20 years in the information technology industry gaining experience in software development, project management, business development, corporate training, and part-time teaching. Matt holds an MS in computer science and an MBA in project management. Besides the first edition of The Object-Oriented Thought Process, Matt has published two other computer books, and more than a dozen articles in magazines and journals such as Dr. Dobb's Journal, The C/C++ Users Journal, Software Development Magazine, Java Report, and the international journal Project Management. Matt has presented at conferences throughout the United States and Canada.