014-004-006
protected Modifier: Inheritance and Encapsulation
Hard
Problem Description
protected Modifier: inheritance and Encapsulation
In this problem, you will create a program that implements a BankAccount class with a protected balance field and a SavingsAccount subclass that inherits from it, reads a deposit amount and interest rate from standard input, and displays the resulting balance to standard output.
Learning Objective: Understand field sharing within inheritance hierarchy using protected access modifier
Overview
The protected modifier allows access from the same package or child classes. It sits between private and public, designed for inheritance-based designs.
Specifications
Create parent class BankAccount:
- protected field
balance(initial value 0) deposit(int amount)method: add to balancegetBalance()method: return balance
Create child class SavingsAccount:
- Extends
BankAccount addInterest(double rate)method: calculate and add interest to balance (balance × rate)- Directly access protected field
balance
- Directly access protected field
In Main class:
- Read deposit amount (integer) and interest rate (decimal) from standard input
- Create SavingsAccount instance
- Deposit the input amount
- Add interest at the input rate
- Output balance
Input Format
amount
rate
Output Format
Balance: <balance>
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up