Implementing Inheritance and Encapsulation in Dart Using a Bank Account System

in CCSyesterday

Hello everyone!

Today I am here to share another practical example of Inheritance in Object Oriented Programming (OOP) in dart.


inheritance & encapsulation.png

We will write a parent class BankAccount with the private variable _balance. It will have two methods deposit() and withdraw(). The we will create a child class SavingAccount which will extend the parent class. It will have a method addInterest() where we will use properties of the parent class such as using balance variable to calculate the amount of interest.


image.png

This is the parent class bank account. There is a private variable balance. I have passed this variable directly using the constructor.

Then I have defined the deposit() method with some conditions to check the deposited amount if it is valid or not. Then I am printing the deposited amount and the balance after the deposit.


image.png

This is the withdraw() method or function to withdraw amount from the balance. I have implemented some conditions to check if the withdrawal amount is valid then it should update the balance otherwise it should throw an exception.


image.png

Here you can see I have created the getter for the private variable _balance to access it in the main class. It is the concept of encapsulation which we have already discussed.

Then I have created the child class which extends the parent class. I have created the constructor as in the parent class using the super keyword. As we know that the saving accounts have some interest so I have added the method addInterest() to calculate the interest on the balance and then returning the updated balance.


image.png

This is the main where I have created the object of the savingaccount class and I am accessing all the attributes and methods of the parent class as well.


image.png

The program is running smoothly and it is following the rules of encapsulation and inheritance in dart object oriented programming language.

Posted using SteemX

Sort:  

🎉 Congratulations!

Your post has been upvoted by the SteemX Team! 🚀

SteemX is a modern, user-friendly and powerful platform built for the Steem community.

🔗 Visit us: www.steemx.org

✅ Support our work — Vote for our witness: bountyking5

banner.jpg

 yesterday 

🎉 Congratulations, @mohammadfaisal!

Your post Implementing Inheritance and Encapsulation in Dart Using a Bank Account System was rewarded by CCS Curation Trail

CCS Logo

“Home is where your heart is ❤️.”

👉 Join the CCS Curation Trail | Community Invitation

Vote Banner

Vote for visionaer3003 as witness