There are four core concepts of OOP such as abstraction, polymorphism, inheritance, and encapsulation.
Abstraction (abstract/interface/base)
- It is used to define a general class that the others need to follow or inherit.
- It contains enough common attributes to figure out the description of the class.
- eg: VehicleAbstract class describes a vehicle but it does not contain specific attributes or types. It could contain some common attributes such as vehicle_name, speed_in_km, manufacturer, etc.
Polymorphism
It describes the concept that we can access objects of different types through the same interface.
All objects in Java are all extended the class Object
. So, they are all polymorphic because they pass at least two instanceof
checks.
1. runtime polymorphism / dynamic method / method overriding
- A process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. We can achieve dynamic polymorphism by using the method overriding.
- A parent class has many children and they override some specific themselves.
class Animal
def make_sound
p this.sound
end def sound
""
end
endclass Duck < Animal
def sound
"wak wak"
end
endclass Dog < Animal
def sound
"bak bak"
end
enddog = Dog.new
dog.make_sound #=> "bak bak"duck = Duck.new
duck.make_sound #=> "wak wak"
2. Static Polymorphism / compile-time polymorphism / method overloading
- In Java, we can define the same method name with different amount / type of parameters.
- In Python and Ruby, there is no allowance to have two methods in the same class or module have the same name (they would override each other). Then, method overloading in these languages means that only one method has a flexible amount of input parameters and the different logic would be handled inside the method.
class Chicken < Animal
CHICKEN_SOUNDS = {
"hen" => "kutak kutak",
"rooster" => "owk owk",
"chick" => "chip chip"
} def chick_type=(new_chick_type)
@chick_type = new_chick_type
end def chick_type
@chick_type
end def make_sound
sound(chick_type)
end def sound(chick_type = "chick")
chick_type = CHICKEN_SOUNDS.keys.first unless CHICKEN_SOUNDS.keys.include? check_type CHICKEN_SOUNDS[chick_type]
end
endchicken = Chicken.new
chicken.chick_type = "hen"
chicken.make_sound #=> "kutak kutak"
Inheritance
- Inherit from an interface, abstract, or base class (ancestor) helps to reduce the time building and make the code more flexible.
- The ancestor class does not need to fulfill all the requirements of the new class, it may have some unused/missing attributes or methods.
Encapsulation
- All attributes and methods that have the same purpose in making a feature or module would be encapsulated into a class.
- Every class needs to cover the attributes themselves (data-hiding). eg: does not allow to set/get an attribute by outside object or method.
- Only allow to get or set or to call custom requests through public methods of the class when all the rules and restrictions are satisfied.