Skip to main content

Are Encapsulation, Polymorphism, and Inheritance peers?

Posted by castelaz on September 24, 2003 at 10:20 AM PDT

I spend most of my time as a Java developer happily writing code without explicitly thinking about encapsulation, polymorphism, and inheritance as underlying principles. I mean those things are given. It would be like noticing wheels are round each time I get in my car. Just like I exploit the roundness of my tires as I tool down the street, I make use of the object-oriented features of Java without necessarily being consciously aware that is what I'm doing.

This isn't to say I drive with my head stored in the trunk, or that I have it shoved somewhere else when I code. Although my family and co-workers may have other opinions, I like to believe I'm concentrating on the things that matter most whether I'm driving or programming. In the case of programming this would include things like fulfilling the spec, designing a system that is maintainable, and writing code that is readable. I don't set out to create a program that exploits polymorphism. I create a program to solve a problem. Encapsulation, polymorphism, and inheritance are means towards that end. They are not the goals.

On the other hand, I'm not neutral in my use of these object-oriented features. When I reflect upon past work, I detect a strong pattern in my code. My greatest concern seems to be with encapsulation. I like to keep as much as I can private. I'm pretty stingy with the public keyword, and rarely, if ever, use protected. Polymorphism creeps silently into a number of my projects, but mostly as separate implementations of a common interface, rather than through extension of another class. In other words, my code tends to emphasis polymorphism over inheritance.

I suspect most of these inclinations date back to my years as a C programmer. I originally encountered the ideas behind The Big Three of OO while coding in that language. I was already doing both encapsulation and polymorphism through the use of module-level variables and function pointers, but without the cool names for the practice. When I migrated over to a true OO language, those two concepts traveled with me. Perhaps I've been damaged somewhere along the line, but I fear inheritance will always come up third in my personal OO lexicon.

Then again, isn't that the real beauty of a rich language like Java. While we can discuss and debate the relative merits of one approach over another, the language is open and flexible enough to allow different interpretations of what is important, and how it should be used.

Related Topics >>