- There are four fundamental ideas in object-oriented programming to keep in mind when creating classes. And they have the wonderful names Abstraction. Polymorphism. Inheritance. And Encapsulation. And one way I like to remember these terms is with the delicious acronym A-P-I-E. A pie! Now, these four words can sound intimidating, but you probably do most of them already in daily thought and conversation, even if you don't use these fancy academic terms to describe them.
Let me prove that with the first one: Abstraction. If I say, 'person' you know what I mean. I didn't specify who I was thinking of. I didn't even describe the person. Male or female. Tall or short. You might have imagined someone in particular. That's OK. But I don't have to get that specific because you understand the idea of a person. You've known and encountered enough real people to abstract the idea of what a person means. Abstraction means we focus on the essential qualities of something rather than one specific example.
By using abstraction, we automatically discard what's unimportant or irrelevant. Your mental model of a person might have a name, a gender, and a height, but it probably doesn't have flavor or icing. Those are things that make sense if I was describing a cookie, but they're irrelevant to the idea of a person. Abstraction means the idea or concept of a person is completely separate from any specific instance. It's what we do all of the time in conversation.
And it's at the heart of object-oriented programming because it's what we're doing when we make a class. I don't create separate classes for each person I need to define in my program. I just focus on the essential qualities of the idea I care about and I write one person class. I'll focus on things like: each person has a name, a height, and a gender. And because I always want to discard what's unimportant, it's never just, what does a person class look like? It's, what should a person class look like for this application? Under these circumstances, at this time.
Focusing always on just the essentials. So it might be true that every person has a height, but if my application doesn't care about that piece of information, then I don't need that attribute defined in my class.
- Object-oriented basics: objects, classes, and more
- Defining requirements
- Identifying use cases, actors, and scenarios
- Domain modeling
- Identifying class responsibilities and relationships
- Creating class diagrams
- Using abstract classes
- Working with inheritance
- Developing software with object-oriented design principles