Awesome!
Completion rate improved to 3.13Sectionย 3. Chapterย 3
single
Challenge: Access Modifiers
Swipe to show menu
Task
Swipe to start coding
Imagine you are creating a digital wallet application. You need to create a DigitalWallet class that represents a userโs wallet where they can store money.
-
Define access modifiers for the class fields:
balanceshould be private to prevent direct modification from outside the class.ownershould be protected to allow access in potential subclasses.- Methods like
addMoneyandshowBalanceshould be public so that external code can safely interact with the wallet.
-
Implement a constructor using the initializer list syntax:
- It should take
ownerNameas a parameter. - Initialize
ownerwith the passedownerName. - Initialize
balanceto0.0.
- It should take
-
Implement the
addMoneymethod:- Check if the amount is greater than 0.
- If yes, add it to
balanceand print a message like"150$ added to Alice's wallet." - Otherwise, print
"Invalid amount!".
-
Implement the
showBalancemethod:- Print the ownerโs name and the current balance in a readable format.
Solution
Everything was clear?
Thanks for your feedback!
Sectionย 3. Chapterย 3
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat