014-004-006
protected Modifier: Inheritance and Encapsulation
Hard
Problem Description
protected Modifier: Inheritance and Encapsulation
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:
- Create SavingsAccount instance
- Deposit 1000
- Add interest at 5% rate (0.05)
- Output balance
Output Format
Balance: 1050
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
