Hello everyone,
I'm preparing for a Java interview and referring to this resource, and I've been reviewing Object-Oriented Programming (OOPs) concepts. I wanted to gather some insights from experienced Java developers and fellow enthusiasts to help me solidify my understanding. Along with that, let's have a hands-on coding challenge related to OOPs concepts.
**Interview Question 1: Explain Inheritance and provide an example**
- Inheritance is a fundamental OOP concept where a class (subclass) can inherit properties and behaviors from another class (superclass). This allows for code reusability and establishing an "is-a" relationship between classes.
**Interview Question 2: What is Polymorphism and how can you achieve it in Java?**
- Polymorphism refers to the ability of a class to take on multiple forms. In Java, it can be achieved through method overloading and method overriding.
**Coding Challenge: Implement a basic Bank Account Hierarchy**
Let's create a simple Bank Account hierarchy using Java classes to demonstrate inheritance and polymorphism. Here are the requirements:
1. Create a base class `BankAccount` with the following properties: - `accountNumber` (int) - `accountHolder` (String) - `balance` (double)
2. Implement a parameterized constructor in the`BankAccount` class to initialize the above properties.
3. Add methods in the `BankAccount` class: - `deposit(double amount)` to add funds to the account. - `withdraw(double amount)` to deduct funds from the account. Ensure sufficient balance before withdrawal.
4. Create two subclasses `SavingsAccount` and `CheckingAccount`, inheriting from `BankAccount`.
5. `SavingsAccount` should have an additional property `interestRate` (double) and a method `applyInterest()` to add interest to the balance based on the interest rate.
6. `CheckingAccount` should have an additional property `overdraftLimit` (double) and a method `withdraw(double amount)` that allows withdrawals even if the balance is less than the withdrawal amount, but within the overdraft limit.
7. Test your classes by creating objects for each type of account and perform some operations like deposit, withdrawal, and applying interest.