OOP is a programming paradigm based on the concept of objects. Objects are used to represent self-contained entities, and they communicate with other objects by sending or receiving messages via well-defined public interfaces(aka public methods).
Each object contains hidden implementations(code) and internal state(data).
Essential Components of OOP
- Classes: blueprint for creating new objects — defines a public interface, code for methods, and data fields. Every time a class is defined, a new type of the same name is created as well.
- Interfaces: a related group of function prototypes for one or more classes to implement. Goal: want a bunch of classes to provide a common set of behaviors but there’s no common implementation to inherit
- Objects: represents a particular “thing”. Each object has its own interface, code, and field values.
- Inheritance: a derived class inherits either the code, the interface, or both from a base class.
- Subtype polymorphism: Code designed to operate on an object of type T can operate on any object that is a subtype of T
- Dynamic Dispatch: The actual code that runs when a method is called depends on the target object, and can only be determined at runtime
- Encapsulation: the bundling of a public interface and private data fields/code together into a cohesive unit
Encapsulation
Encapsulation is the guiding principle behind the OOP paradigm, and there are 2 facets to encapsulation:
- Bundle related public interface, data, and code together into a cohesive, problem-solving machine
- Hide data/implementation details of that machine to clients.
By doing so, coupling is reduced between modules, and better modularity is achieved.
Encapsulation and Access Modifier
Languages provide “access modifiers” which are keywords/syntax that specify the visibility/accessibility of a class’s method and fields to code outside the class.
Generally, there are three levels of access visibility
- Public: All member or outside function can access
- Protected: Protected method or data member or any subclass derived can access