Get ready to take a trip to a foreign country. It’s time to visit Objectville, a land where objects do just what they’re supposed to, applications are all well-encapsulated (you’ll find out exactly what that means shortly), and designs are easy to reuse and extend. But before we can get going, there are a couple of things you need to know first, and a few language skills you’re going to have to learn. Don’t worry, though, it won’t take long, and before you know it, you’ll be speaking the language of OO like you’ve been living in the well-designed areas of Objectville for years.
Whether this is your first trip to Objectville, or you’ve visited before, there’s no place quite like it. But things are a little different here, so we’re here to help you get your bearings before you dive into the main part of the book.
We’re going to talk about classes and objects a lot in this book, but it’s pretty hard to look at 200 lines of code and focus on the big picture. So we’ll be using UML, the Unified Modeling Language, which is a language used to communicate just the details about your code and application’s structure that other developers and customers need, without getting details that aren’t necessary.
One of the fundamental programming topics in Objectville is inheritance. That’s when one class inherits behavior from another class, and can then change that behavior if needed. Let’s look at how inheritance works in Java; it’s similar in other languages, too:
Polymorphism is closely related to inheritance. When one class inherits from another, then polymorphism allows a subclass to stand in for the superclass.
Encapsulation is when you hide the implementation of a class in such a way that it is easy to use and easy to change. It makes the class act as a black box that provides a service to its users, but does not open up the code so someone can change it or use it the wrong way. Encapsulation is a key technique in being able to follow the Open-Closed principle. Suppose we rewrote our Airplane
class like this:
Encapsulation is when you protect information in your code from being used incorrectly.
This change means that the rest of your app no longer has to call setSpeed()
to set the speed of a plane; the speed
variable can be set directly. So this code would compile just fine: