Object Oriented Principals — in Plain English
This post talks about Object Oriented primitive concepts. When you are writing code, you know how to declare a method as private or how to subclass from a class, instead here I tried to explain what the concepts in plain english. Here is a simple reasonable explanation of each in case you want to explain it to a six year old:
Inheritance allows us to subclass from a class. In object oriented programming classes are all members of hierarchy and it is possible only with the help of Inheritance. Child class inherits methods and properties form the parent. This enables the developers to reuse the code easily.
Abstraction means representing essential features without including implementations. What does that mean? Abstraction is a concept or paradigm of describing things in simpler terms (abstract details) depending on its location in inheritance hierarchy. It helps representing essential features without being worried about the implementation. At the most abstract level there is no implementation details. More abstract concepts are at the top and more concrete ideas go to the bottom. This graph represent a general idea of abstraction concept:
Interface is a set of methods with no implementations. Abstract classes contain both abstract and concrete methods and they must be inherited.
Encapsulation is used to define, hide and restrict properties and methods outside access. It prevents unnecessary access to methods and properties (class is container encapsulating the data). The access is available only if required, this handles by access modifiers:
- Public: Accessible from everywhere
- Protected: Accessible within the same package and subclasses
- Default (no specifier): Accessible form inside the package
- Private: Only accessible within the same class, not visible to subclasses
Access Modifiers in Swift can be an example.
Polymorphism give us availability to define a method (in subclass) that is already declared in the parent class. Generally there are two types of polymorphism:
- Compile time polymorphism or overloading:
You can define several methods with the same name, the only difference will be the method signatures.
- Run time polymorphism or overriding:
You can define methods with the same name and signature as parent class (or the implemented interface). This gives us ability to define the methods that is specific to particular subclass.