I enjoy object-oriented programming. I understand the concepts, but I’ve found that when asked to define or show an example of the basic principles my brain blanks. This especially happens in pressure situations like interviews. So this post gets to act as my memory until the four principles of object-oriented programming (encapsulation, inheritance, polymorphism and abstraction).
Encapsulation
Encapsulation is the idea that the attributes of an entity are enclosed in that entity. This gives context to attributes. This also allows the programmer to restrict access to those attributes so that those attributes are modified and/or used only in ways that the programmer intends to use them.
Inheritance
Inheritance is the idea that an entity can inherit attributes from another entity. It allows the programmer to create similar entities without needing to redefine similar attributes over and over.
This means every Dog, Cat and Bird (subclasses) will have a name and age attributes as well as an Identify method because they are Animals (superclass).
Polymorphism
Polymorphism means “having many forms” which honestly doesn’t really help too much as a definition. I like to call it a way to have the same method, only different. There are two ways to do this:
- Overloading: The method name stays the same, but the parameters, the return type and the number of parameters can all change.
- Overriding: This is when a subclass method has the same name, parameters and return type as a method in a superclass but has a different implementation.
A few rules about method overriding in Java…- Subclass methods should have the same return type and arguments
- The access level of the subclass method cannot be more restrictive than the superclass method.
- A method declared final or static cannot be overridden.
- If a method cannot be inherited, it cannot be overridden.
Abstraction
Abstraction is the process of hiding all but the relevant information about a thing to make things less complex and more efficient for the user. For example, we don’t need to know how a clock works in order to use it to tell time. Abstraction lets you focus on what the thing does instead of how it does it.
As much as I tried to keep thins post brief, I failed. If I got something wrong, or if something doesn’t make sense please reach out and let me know.
Here are a few of the resources I used: