Polymorphism


Poly means many and morphism means forms so Polymorphism is the ability of a variable, object, or function to take on multiple forms(for example A man is father, brother, worker, etc)
Benefits of Polymorphism: 
  • Code Reusability:
  • Flexibility:

There are 2 types of Polymorphism
  1. Compile-Time Polymorphism (Method Overloading).
  2. Run-Time Polymorphism (Method Overriding).

Practice Task:

Compile-Time Polymorphism (Method Overloading).

Q1:Create a class Calculator with overloaded methods to perform addition, subtraction, multiplication, and division for different numeric types (int, double). Demonstrate the usage of these methods.
Implement a class MathUtility with overloaded methods to calculate the square of an integer, the square of a double, and the cube of an integer. Display the results of these calculations.

Run-Time Polymorphism (Method Overriding).

Q1:Create a base class Shape with a method area() and then create subclasses like Circle, Rectangle, and Triangle that overrides the area() method. Demonstrate polymorphism by calculating and displaying the areas of different shapes.
Q2:Design a base class Vehicle with methods start() and stop(), and then create subclasses like Car, Motorcycle, and Bus that override these methods. Show how polymorphism allows you to start and stop different vehicles seamlessly.
Q3:Develop a base class Employee with a method calculateSalary(), and then create subclasses like Manager, Engineer, and Salesperson that override this method. Use polymorphism to calculate and display the salaries of different employees.
Q4:Design a base class Animal with methods like makeSound() and move(), and then create subclasses like Dog, Cat, and Bird that override these methods. Showcase how polymorphism allows different animals to make sounds and move uniquely.
Q5:Create a base class Payment with a method processPayment() and subclasses like CreditCard, PayPal, and BankTransfer that override this method. Use polymorphism to process different payment methods.
Q6:Design a base class MediaPlayer with methods like play() and stop(), and then create subclasses like AudioPlayer, VideoPlayer, and ImagePlayer that override these methods. Demonstrate how polymorphism enables different types of media to be played and stopped.
Q7:Extend the employee hierarchy (e.g., Employee, Manager, Engineer) with a new method, such as displayInfo(), and demonstrate polymorphism by displaying information for different types of employees. 
Q8:Create a base class Product with methods like calculatePrice() and displayInfo(), and then create subclasses like Electronics, Clothing, and Books that override these methods. Use polymorphism to calculate prices and display info for different product types. 
Q9:Develop a program to draw different shapes (e.g., circles, squares) using polymorphism. Implement a base class Shape with a method draw(), and then create subclasses for each shape type. 
Q10:Design a system for an online store with different types of products (e.g., electronics, books). Create a base class Product with methods like getDescription() and getPrice(), and then create subclasses for each product category to demonstrate polymorphism.

High-Level Programs

Q1:A company pays its employees on a weekly basis.

The employees are of four types:

Salaried employees are paid a fixed weekly salary regardless of the number of hours worked

Hourly employees are paid by the hour and receive overtime pay (i.e., 1.5 times their hourly salary rate) for all hours worked in excess of 40 hours

Commission employees are paid a percentage of their sales

Base-salaried commission employees receive a base salary plus a percentage of their sales. The company wants to write an application that performs its payroll calculations polymorphically.

Q2:Create an inheritance hierarchy that a bank might use to represent customers’ bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e., credit or debit).

Create an inheritance hierarchy containing base class Account and derived classes Savings-Account and CheckingAccountthat inherit from class Account.

In this task we are managing 5 accounts of saving-accounts and 5 of checking-accounts (use arraylist to add account).

Base class Account should include one data member of type double to represent the account balance. ,intaccountNumber,and String BankName (Final).

· The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it’s greater than or equal to 0.0. If not, the balance should be set to 0.0 and the constructor should display an error message, indicating that the initial balance was invalid. Also provide BankName here.

· The class should provide three member functions. Member function credit should add an amount to the current balance and return “true” Boolean type.

· Member function debit should withdraw money from the Account and ensure that the debit amount does not exceed the Account’s balance. If it does, the balance should be left unchanged and the function should return “false” Boolean type.

· Setters and getters for data members except BankName as this is final.

· Tostring()s

Derived class SavingsAccount should inherit the functionality of an Account, but also include a data member of type double indicating the interest rate (percentage) assigned to the Account.

· SavingsAccount’s constructor should initial value for the SavingsAccount’s interest rate.

· SavingsAccount should provide a public member function calculateInterest that returns a double indicating the amount of interest earned by an account.

· Member function calculateInterest should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redefining them.]

· Tostring()



Derived class CheckingAccount should inherit from base class Account and include an addi- tional data member of type double that represents the fee charged per transaction.

· Checking- Account’s constructor should receive a parameter indicating a fee amount.

· Class CheckingAccount should redefine member functions credit and debit so that they subtract the fee from the account balance whenever either transaction is performed successfully. CheckingAccount’s versions of these functions should invoke the baseclass Account version to perform the updates to an account balance.

· CheckingAccount’s debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance).

[Hint: Define Account’s debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.]

· Tostring()

After defining the classes in this hierarchy, write a program that creates an of Accountand make following menu:

1) Add Account (saving or checking): This will add account type based on user choice.

2) Deposit Amount: This will add amount to the respective account and then print proper transaction slip to user.

3) Withdraw Amount: This will deduct amount to the respective account and then print proper transaction slip to user.

4) Exit.