Encapsulation and Abstraction
Abstraction shows only the necessary details of an application, and serves as a fundamental way to manage complexity.
This key feature of C# reveals only the relevant information to the user, aids the user in managing a complex system, supports code reuse, supports polymorphism of modules, and simplifies code.
A motorcyle has a make, model, design, engine, brakes, lights, seat, and other various qualities and components; however, the rider only cares about general function. Abstraction removes the excess much like an automatic transmission compared to a manual.
In encapsulation, data and functions are combined in a logical or physical package. This allows for the prevention of access to details of an application considered nonessential to the user. This mechanism binds data with code in a safe way to prevent data corruption, improve flexibility, improve extensibility, and reduce code bunching.
Though abstraction and encapsulation differ, they share common features such as encapsulation providing vehicles for packaging information, which abstraction uses to hide irrelevant information.
Access level specifiers define the scope of a class member. Access specifiers can be used to implement abstraction and encapsulation. Specifiers control visibility:
- Public – These classes can be accessed by any outside classes.
- Private – These classes cannot be accessed by any outside classes.
- Protected – These classes can only be accessed by their child classes.
- Internal – These classes can only be accessed by classes in the same assembly.
- Protected internal – These classes can only be accessed by child classes or classes in the same assembly.
The table below outlines access levels:
|Specifiers||Objects of other classes within the namespace can access||Objects of child classes inside the namespace can access||Objects of other classes beyond the namespace can access||Objects of child classes beyond the namespace can access|