It is a programming concept based on objects having data and methods defined in the class to which it belongs.
Then Concept Include: Encapsulation, Inheritance, Abstraction and Polymorphism.
Encapsulation:
It is a mechanism of wrapping the variables/data and methods operate on the variables/data together as a single unit.
Example:
- I have Spring boot application add data into data base and I’m using Object Relational Mapping (ORM), so I will define DAO - Data Access Object class to interact with data base table customerAccounts, this call will include private variables and public setters and getters.
Inheritance:
It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class.
Example:
- The
Accountclass serves as the base class, containing common functionalities such as deposit, withdraw and getBalance. - The
SavingsAccountclass adds acalculateInterestmethod to calculate interest specific to savings accounts, while theCheckingAccountclass adds aprocessCheckmethod to handle check processing specific to checking accounts. - Through inheritance, the code is more organized, and common functionalities are centralized in the base class, reducing code duplication and promoting reusability.
Overriding:
- The
Accountclass defines common functionality for all types of accounts, including deposit and withdraw methods. - The
SavingsAccountandCheckingAccountclasses extend theAccountclass and override withdraw methods as need to calculate different fees for each account type.
Abstraction
Allows to generalize functionality of classes without providing implementation details.
Example (Interface):
- I have customerService interface that contracts that define a set of methods that a class must implement. then I have customerServiceImp class which implements all interface methods and give their implementation.
Example (Abstract):
- For banking system we have a Accounts abstract class which has abstract methods like (withdraw & deposit) methods and other non abstract methods (getBalance).
- We extend Accounts abstract class it’s provide different implementation for abstract methods and inherent non abstract methods (getBalance).
Polymorphism:
It means many forms, and we achieve this by Overloading (compile) and Overriding (runtime).
Example (Overloading):
- In banking system we have*
Transaction* class contains multiple overloaded*transfer()* methods, each accepting different parameters to handle different types of transactions transfer.
Example (Overriding):
- The
Accountclass defines common functionality for all types of accounts, including deposit and withdraw methods. - The
SavingsAccountandCheckingAccountclasses extend theAccountclass and override withdraw methods as need to calculate different fees for each account type.
Top comments (0)