oop
10. Hierarchical Inheritance: Type Checking
Analyze the code, write your predicted output, and then reveal the solution.
Scenario
Multiple classes inherit from the same parent. How do we distinguish between them at runtime?
Code Block
class Account { void info() { System.out.println("Basic Account"); } } class SavingsAccount extends Account { void interest() { System.out.println("5% Interest"); } } class CurrentAccount extends Account { void overdraft() { System.out.println("Overdraft enabled"); } } public class Main { public static void main(String[] args) { Account[] accounts = { new SavingsAccount(), new CurrentAccount() }; for (Account acc : accounts) { if (acc instanceof SavingsAccount) { ((SavingsAccount) acc).interest(); } else if (acc instanceof CurrentAccount) { ((CurrentAccount) acc).overdraft(); } } } }
Take Your Shot
Predicted Output
Type exactly what you think will be printed in the console.