OOP Principles
Abstraction
Can be achieved by:
-
Exposing a limited set of public methods
-
Exposing an interface
-
In statically typed languages abstract base classes(ABC) or Interfaces are used to define abstractions. Same can be achieved in dynamically typed languages such as python/js using
duck typing
class Duck:
def quacks(self):
print("Imma duck")
class Frog:
def quacks(self):
print("Imma frog")
def quack(qackable):
# Anything that can quack will quack
# We're good as long as the signature matches
qackable.quacks();
quack(Duck())
quack(Frog())
Encapsulation
Amplify the essential while suppressing the details.
public
access modifiers are self documenting API's of a class. A well chosen limited set ofpublic
methods amplifies the essentials to the users.private
access modifiers restrict the scope of altering the internal state in an unintended way.
Polymorphism
- Ad-hoc : Method overload
void print(Person person) {
System.out.printf("Name %s Age %d", person.name, person.age);
}
void print(Company company) {
System.out.printf("Name %s Age %d", company.name);
}
- sub-typing: Inheritance, method override. Reduced multiple if statements to 1(construction)