Thursday, August 04, 2022

Object Oriented Concept For Programmer 2022

Object Oriented Concept For Programmer

This is for beginners.

I try to explain object oriented programming is different ways, especially for beginners.

There are 4 things in OOP: Abstraction, Inheritance, Encapsulation and Polymorphism.

Example: Shape (abstraction)

Shape has area, this is abstract. You don't how's the shape looks like (circle? triangle?), and you are not sure about the size of the shape.

Shape().area # let's say this is how you define the Shape() object.

Example: Circle (Inheritance)

Circle is a shape, so circle has area. Why? Circle inherit the area properties from Shape.

Circle() is Shape()

Example: Circle (Encapsulation)

You don't allow anyone to change the area of a circle. The area of a circle can only be change by the radius. I use the private keyword to protect the Circle().area.

private Circle().area
Circle().area= pi * radius * radius
Circle().get_area()= area

Direct access of area outside of the object invoke an error:
print Circle().area ==> error
print Circle().get_area() ==> 20.5

Example: Square and rectangle (Polymorphism)

Square and rectangle are similar. Square is another form of rectangle, or you can say that rectangle is another form of square.

Square() is Shape()
Square().get_area(height)= height * height # formula for square
Square().get_area(height,width)= height * width # formula for rectangle

You can have 2 functions with the same name for Square() object, this is polymorphism.

print Square().get_area(5)
print Square().get_area(5,4) # this is for rectangle

Note: In C programming language, there are 2 commands for string copy 1. strcpy(t,s) 2. strncpy(t,s,n). In OOP, you can merge these 2 commands into 1 with the same name, but differentiate by number of parameters.