SLC S22 Week3 || Inheritance and Polymorphism in JAVA

in dynamicdevs-s22w3 •  6 days ago 

Hello everyone! I hope you will be good. Today I am here to participate in the contest of @kouba01 about The Object Approach In JAVA. It is really an interesting and knowledgeable contest. There is a lot to explore. If you want to join then:



Join Here: SLC S22 Week3 || Inheritance and Polymorphism in JAVA





Designed with Canva

Understanding Inheritance

Write a Java program that creates a Person class with attributes name and age. Then, create a Student class that inherits from Person and adds the attribute studentId. Demonstrate how to create objects of both classes and display their details.

Inheritance is one of the most widely used programming concepts of the object oriented programming and it is of great use to inherit the classes ion the programming. So before writing the program I will first explain the the concept of this program by using a class diagram. The class diagram is given below:


image.png

Here you can see the major class is Person with the attributes name and age and then there is the second class Student with the attribute studentId. And the arrow sign from Student class to Person class demonstrates that the student class is inherited from the person class.

Now let us move towards the program to understand how we can implement it with the help of the code.

1. Base Class: Person


image.png

This is the base class Person and its details are given below:

Attributes:

  • name and age are private attributes of this Person class. It ensures the encapsulation.

Constructor:

  • As we know that the constructor is the function which has the same name as the class name and it is called automatically when the object of the class is created. The constructor Person() accepts name and age as parameters to initialize the attributes when a Person object is created.

Methods:

  • displayDetails(): This method prints the name and age attributes.
  • These methods provide the basic functionality for a Person.

2. Derived Class: Student


image.png

This is the derived class visualizing the concept of the inheritance. Here are the details of the derived class Student:

Inheritance:

  • The Student class extends the Person class. It means it inherits all the non-private members whether they are the methods or attributes.

New Attribute:

  • This class adds a studentId attribute which is specific to Student.

Constructor:

  • The constructor of the class Student uses super(name, age) to call the parent class (Person) constructor. This initializes name and age in the base class.
  • Then it initializes the studentId attribute within the Student class.

Method Overriding:

  • The displayDetails() method is overridden to include the studentId in addition to the name and age from the parent class.
  • super.displayDetails() ensures that the original functionality from Person class is preserved.

3. Main Class: Inheritance


image.png

This is the main class to control the program. The details of this main class are given below:

  • As we need to create the object of the class in the main to use it so I have created the object of the Person class with the name person.It is created using its constructor and displays its details using displayDetails().
  • Then to access the Student class its object (student) is created. This calls the Student constructor which in turn calls the Person constructor via super().
  • When displayDetails() is called on the student object then the overridden version in the Student class is executed. This demonstrates method overriding.

inheritance-ezgif.com-optimize.gif

Here you can see that I have inherited the attributes of the Person class in the Student class. It is how we can use the concept of the inheritance and reduce the code redundancy. It is very useful while reusing the same code for the same sections.



Create a Shape class with overloaded methods area() to calculate the area of different shapes (circle, rectangle, and triangle) based on the provided parameters.

First of all in order to calculate the area of the shapes circle, rectangle and triangle we need to understand and know their formulas. Each shape has a specific formula which is used to calculate the area of that shape with any parameters.

Here are the formulas for the mentioned shapes:

Area of circle = Pi * r 2

Area of rectangle = length * width

Area of triangle = 1/2 * base * height

I will use these formulas for the calculation of the areas of these shapes by using the java program with the overloaded method.

Here is the implementation of the Shape class with overloaded methods area() to calculate the area of a circle, rectangle and triangle:


image.png

Here you can see that according to the requirements I have created the class Shape(). And in this class there are the overloaded methods for the calculation of the area of the circle, rectangle and triangle. Each method has a different formula according to the shape. The three overloaded methods are given below:

  • First overloaded method is used to calculate the area of the circle by using the specific formula Pi * r 2 for that shape as defined above and in the code. This formulas accepts the constant value of Pi and the radius of the circle.

  • Second overloaded method is used to calculate the area of the rectangle by using the formula length * width. It accepts the length and width of the rectangle to calculate its area.

  • Third overloaded method is used to calculate the area of the triangle by using the formula 1/2 * base * height. This formula accepts the the base of the triangle and the height of the triangle. In this method I have used boolean isTriangle to ensure that this method is specially for the triangles.


image.png

In the main I am calling the same method name area with the different parameter lists to calculate the areas of the different shapes. It shows the usage of the polymorhpism where I am using the same method name for the different purposes.

ezgif.com-optimize (1).gif

Here you can see the output of the program which is calculating the area of the different shapes depending upon the values by using the method overloading concept.



Develop a Bank class with a method getInterestRate(). Create two derived classes SavingsBank and CurrentBank that override the getInterestRate() method to return specific rates. Write a program to display the interest rates for both types of banks.

Before moving towards the program I am making the UML diagram of this statement to understand the working of the program graphically.

image.png

Here in the above diagram you can see that there is a base Bank class at the top. Then there are two further derived classes savingsBank and currentBank and these are derived from the base class Bank and these are using the same method getInterestRate() method means they are utilizing the concept of the method overriding.

Here is the implementation of the Bank class and its derived classes SavingsBank and CurrentBank by using the java language:

Base Class Bank:

image.png

  • At the top I have defined the base class Bank and from this I will derive the next two classes.
  • This base class defines the getInterestRate() method. And this method returns a default interest rate of 0.0%.

Derived Classes:

According to the requirements there are two derived classes which are given below:

  • SavingsBank
  • CurrentBank

SavingsBank:

image.png

  • This derived class from the Bank class overrides getInterestRate() method from the base class and it returns 3.5%.

CurrentBank:

image.png

  • This is also a derived class and it also overrides the getInterestRate() method from the base class to return 1.0%.

Both the derived classes return specific interest rates by using this method getInterestRate().

Main Program:

image.png

Here is the main of the program to control it's working and call the methods to check the working.

  • First of all I have created the instances of SavingsBank and CurrentBank and called their respective getInterestRate() methods to display the specific rates.

overriding-ezgif.com-optimize.gif

  • After running the program we can see different interest rates according to the the type of the bank. Savings bank account has interest rate of 3.5% and similarly current bank has interest rate of 1.0%.

This implementation shows the concept of method overriding. In this implementation the derived classes override the method of the base class to provide specific behaviour.



Polymorphism in Action

Create a class hierarchy with a base class Vehicle and derived classes Bike and Truck. Implement a method startEngine() in the base class and override it in the derived classes to display specific messages. Use polymorphism to call the methods through a base class reference.

Before moving towards the code I will again make the UML diagram for this problem for the better understanding and concept.

image.png

Here in the diagram we can see that there is a base class Vehicle and then there are two more classes which are derived from the base class. These derived classes are Bike and Truck. There is a method startEngine() which is with the same name in all the classes which again utilizes the concept of the method overriding in this problem as well.

image.png

Here is the implementation of the code and the explanation how it demonstrates polymorphism in action:

Base Class (Vehicle)

image.png

  • The Vehicle class represents the parent class for all types of vehicles.
  • It includes a general method startEngine() that prints a message suitable for any vehicle.

Derived Classes (Bike and Truck)

image.png

  • Both Bike and Truck extend the Vehicle class, inheriting its properties and methods.
  • These classes override the startEngine() method to implement behavior specific to their type:
    • Bike: Prints "Starting the engine of the bike... Vroom!"
    • Truck: Prints "Starting the engine of the truck... Rumble!"

Polymorphism

image.png

  • Polymorphism allows a parent class reference (Vehicle) to refer to objects of derived classes (Bike and Truck).
  • This feature enables the program to decide at runtime which method to invoke depending on the actual object type the reference points to.
  • Even though startEngine() is called on a Vehicle reference the overridden method in the derived class (Bike or Truck) is executed.

polymorphism-ezgif.com-video-to-gif-converter.gif

How Polymorphism Works Here

  1. Dynamic Method Dispatch:

    • The Java Virtual Machine (JVM) determines at runtime which method to invoke based on the actual type of the object being referenced.
    • This mechanism is called dynamic method dispatch or runtime polymorphism.
  2. Code Reusability and Flexibility:

    • The base class (Vehicle) provides a generic structure and functionality.
    • The derived classes enhance this functionality to suit specific needs, making the code extensible and easier to maintain.


Build a Library Management System that uses inheritance and polymorphism. Create a base class Item with attributes id, title, and isAvailable. Extend it into derived classes Book and Magazine with additional attributes. Implement polymorphic methods to borrow and return items, and display their details.

image.png

This is the simple UML diagram to understand the concept and working of this library management system. At the end I will provide more extensive UML diagram to understand the flow of the complete library management system.

This Library Management System is designed to manage various types of library items like books and magazines. It uses object-oriented programming principles such as inheritance and polymorphism to handle common functionalities and allow item-specific behaviours.

Base Class: Item

image.png

Here according to the requirements I have created the Item class which serves as the parent class. I have defined the shared properties and behaviours of all library items in this base class.

Attributes:

  • id: A unique identifier for each item.
  • title: The title of the item.
  • isAvailable: A boolean indicating if the item is available for borrowing.

Methods:

  • borrowItem(): Updates isAvailable to false and provides feedback.
  • returnItem(): Updates isAvailable to true and provides feedback.
  • displayDetails(): Displays the item's basic details.

Derived Classes

There are two derived classes in this system where one derived class is Book and the other derived class is Magazine`. Here is the detail of all the derived classes:

Class: Book

image.png

  • It extends the Item class which is a base class.
  • It adds a new attribute author to store the name of the author of the book.
  • It overrides displayDetails() to include the name of the author.

Class: Magazine

image.png

  • It extends the Item class which is the base class.
  • It adds a new attribute issueNumber to represent the issue number of the magazine.
  • It overrides displayDetails() to include the issue number.

Main Class: LibraryManagementSystem

image.png

This class contains the main logic of the program including the menu driven interface and methods for user operations.

Features

Library Initialization (initializeLibrary)
image.png

  • Adds pre-defined books and magazines to the library for demonstration purposes.

Menu-Driven Interface:

  • A loop displays options for users to perform various operations like displaying items, borrowing, returning, and adding items.

Operations

Display Items (displayItems)
image.png

  • Iterates over the libraryItems list and calls the displayDetails() method for each item.
  • Demonstrates polymorphism as the appropriate displayDetails() method (from Book or Magazine) is called dynamically.

Borrow Item (borrowItem)
image.png

  • Prompts the user for an item ID.
  • Locates the item in the libraryItems list.
  • Calls the borrowItem() method, which updates availability and provides feedback.

Return Item (returnItem)
image.png

  • Similar to borrowItem, but it calls the returnItem() method to mark the item as available.

Add Item (addItem)
image.png

  • Allows users to add new Book or Magazine objects by inputting details (ID, title, and specific attributes).
  • Adds the newly created object to the libraryItems list.

Error Handling:

  • Prevents invalid operations such as borrowing an unavailable item or adding an item with an incorrect type.

libsystem-ezgif.com-optimize.gif

Key Concepts

Inheritance

  • The Book and Magazine classes inherit attributes (id, title, isAvailable) and methods (borrowItem, returnItem, displayDetails) from the Item class.

Polymorphism

  • The displayDetails method is overridden in the derived classes to provide specific details for books and magazines.
  • The libraryItems list is of type Item. When calling displayDetails(), the method of the actual object's class (Book or Magazine) is invoked dynamically.

image.png

Here is the complete working of the program with the help of the UML diagram where at the top there is a library management system and the and then in that system there is a base Item class which has two derived classes Book and Magazine.



Employee Management System

An organization employs three types of workers: contractual employees, permanent employees, and hourly workers.

Here is the UML diagram of this employee management system. It helps to understand the connection of the classes with each other and shows how the derived classes are linked with the base class.

image.png

Here if we see the diagram at the top there is the base class with the name Employee and then there are three derived classes such as HourlyWorker, ContractualEmployee and PermanentEmployee.

The system models an Employee Management System for an organization that manages three types of employees: contractual, permanent and hourly workers. Each employee type has unique salary calculation rules and attributes, but they all share common information such as name, CIN (Employee ID) and address. The program uses object-oriented programming principles like inheritance, abstraction and polymorphism to achieve a clean, reusable and modular design.

Base Class: Employee

image.png

The Employee class serves as the parent class for all employee types. It encapsulates the shared attributes and behaviours of employees:

Attributes:

It has these following attributes:

  • name: Represents the employee’s full name.
  • CIN: A unique identifier for each employee.
  • address: Stores the employee’s residential address.
  • salary: Holds the calculated salary of the employee, initialized to 0.0.

Constructor:

  • There is a constructor of the Employee class and this constructor initializes name, CIN and address attributes.

Abstract Method calculateSalary():

  • This method is declared as abstract method and it enforces the derived classes to implement their specific salary calculation logic.
  • Each derived class implements this method according to the respective rules for salary computation.

display() Method:

  • This method prints the common attributes such as name, CIN, address, and salary of the employee.
  • This method is inherited and used in all derived classes to avoid the code duplication.

Derived Classes

In this program each derived class extends the Employee base class and provides specific functionality related to the type of the employee:

ContractualEmployee:

image.png

  • Represents employees with a fixed monthly salary.
    Attributes:
    • monthlySalary: Stores the fixed monthly salary.
      calculateSalary():
    • Assigns monthlySalary to the salary attribute.
      display():
    • Calls the base class display() method to print employee details and salary.

PermanentEmployee:

image.png

  • Represents employees with a base salary and an additional performance bonus.
    Attributes:
    • baseSalary: The fixed base salary for the employee.
    • performanceBonus: Additional compensation based on the employee’s performance.
      calculateSalary():
    • Computes the total salary by summing the baseSalary and performanceBonus.
      display():
    • Calls the base class display() method, appending additional details for permanent employees.

HourlyWorker:

image.png

  • Represents employees paid based on the hours worked and the hourly rate.
    Attributes:
    • hoursWorked: Number of hours worked by the employee.
    • hourlyRate: Pay rate per hour.
      calculateSalary():
    • Computes the total salary by multiplying hoursWorked by hourlyRate.
      display():
    • Similar to other derived classes, calls the base class display() method.

Main Program: EmployeeManagementSystem

The main program demonstrates the usage of the class hierarchy by creating a list of employees and performing operations like salary calculation and displaying employee details.

image.png

  • The program uses a Vector<Employee> to store objects of different employee types such as ContractualEmployee, PermanentEmployee and HourlyWorker.
  • This is possible because all derived classes are treated as objects of the Employee type.

Adding Employees:

  • Three employees of different types are created using their respective constructors:
    • ContractualEmployee: Receives a fixed monthly salary.
    • PermanentEmployee: Has a base salary and a performance bonus.
    • HourlyWorker: Requires the number of hours worked and the hourly rate.

Salary Calculation:

  • Iterates over the list of employees, calling the calculateSalary() method for each.
  • Polymorphism ensures that the appropriate calculateSalary() implementation is invoked based on the runtime type of the object.

Displaying Details:

  • The display() method is called for each employee, printing their details in a formatted manner.
  • Overridden display() methods ensure that each employee type is correctly identified in the output.

empmanagement-ezgif.com.gif

Here in the output you can see the salary of the three different types of employees:

  • At first the salary of the contractual employee is $3000 which is fixed and it cannot be changed.

  • Then there is a second employee and it has the total salary of $3000 but in this the base salary is only $2500 and the remaining $500 is the bonus of for the permanent employee.

  • Then there is the third employee who is an hourly worker and the total salary of that worker is $2400. And the worker has worked for the 120 hours and the per hour salary was $20 and that is why the total salary for the hourly worker is $2400.



Understanding Class Relationships

Given the following class definitions, analyze whether the instructions 1 to 8 in the main method are valid. If invalid, specify whether the error occurs at compilation or runtime.

Let us go through each instruction step by step and analyze whether it is a valid or not on the basis of the class hierarchy:

Class Hierarchy

  • C1 is the base class.
  • C11 extends C1 so it is a subclass of C1.
  • C111 extends C11 so it is a subclass of C11 and by inheritance it is also a subclass of C1.

Instructions:

  1. Instruction 1: o1 = o2;

    • Valid.
      o2 is a C11 object, and C1 o1 can reference a C11 object because C11 is a subclass of C1.
  2. Instruction 2: o1 = o3;

    • Valid.
      o3 is of type C111, and o1 is of type C1, so a reference to a C111 object can be assigned to a C1 reference, since C111 is a subclass of C1.
  3. Instruction 3: o3 = o1;

    • Invalid (Compilation error).
      o1 is of type C1, but o3 is of type C111. You cannot assign a C1 object to a C111 reference unless you know for sure that o1 refers to a C111 object (which cannot be guaranteed here). This causes a compilation error.
  4. Instruction 4: o4 = o5;

    • Valid.
      o5 is of type C1, and o4 is of type C11. Since C11 is a subclass of C1, assigning o5 (of type C1) to o4 (of type C11) is valid, as long as the object referenced by o5 is of type C11 or its subclass (which is the case with o5 referring to a C111 object).
  5. Instruction 5: o3 = (C111) o1;

    • Invalid (Runtime error).
      o1 is of type C1, but it doesn't necessarily refer to a C111 object (it could refer to any object of type C1). Trying to cast a C1 object to C111 will result in a ClassCastException at runtime if o1 is not actually an instance of C111.
  6. Instruction 6: o4 = (C11) o5;

    • Valid.
      o5 is of type C1, but since o4 is of type C11, and C11 is a subclass of C1, casting o5 to C11 is valid. This cast will succeed at runtime if o5 refers to a C11 or C111 object.
  7. Instruction 7: o4 = (C111) o2;

    • Invalid (Runtime error).
      o2 is of type C11, but casting it to C111 will fail at runtime if o2 is not an instance of C111. Since o2 is a C11, this cast will throw a ClassCastException at runtime if o2 is not actually a C111 object.
  8. Instruction 8: o3 = (C11) o5;

    • Invalid (Runtime error).
      o5 is of type C1, but casting it to C11 and assigning it to o3 (which is of type C111) will result in a runtime error if the object referenced by o5 is not an instance of C111. The cast will succeed only if o5 refers to a C111 object, and even then, assigning it to a C111 reference is invalid because it is being cast to C11.

Summary

  • Instruction 1: Valid
  • Instruction 2: Valid
  • Instruction 3: Invalid (Compilation error)
  • Instruction 4: Valid
  • Instruction 5: Invalid (Runtime error)
  • Instruction 6: Valid
  • Instruction 7: Invalid (Runtime error)
  • Instruction 8: Invalid (Runtime error)


Geometric Inheritance

In the geometric inheritance I will use the object oriented programming concepts. According to the requirements I will create three classes Point, Rectangle, and Parallelogram. Each class will be built upon the previous one as per the instructions. According to this rectangle class will be inherited from the point class and similarly Parallelogram will be inherited from its previous class which is Rectangle.

Here is the step by step implementation of the program to complete the requirements of the task.

1. Point Class

image.png

  • This Point class represents a point in a 2D space with x (abscissa) and y (ordinate) coordinates.

Attributes:

  • It has attributes x and y which are private. They ensure encapsulation concept.

Constructors:
This class has the following constructors:
- Point(): This constructor initializes a point where the x co-ordinate is at 0 as well as y co-ordinate is also 0.
- Point(double x, double y): This constructor initializes a point at the given coordinates (x, y).
- Getters/Setters: These methods allow to control the access to x and y.
- toString(): This toString method provides a string representation like Point(x=2.0, y=3.0).


2. Rectangle Class

image.png

  • This class is inherited from Point. It represent a rectangle in a 2D space. It adds two new attributes: length and width.
  • *For the inheritance it uses the super keyword to call the constructor of the parent class Point to initialize x and y coordinates.

Attributes:
This class has the following attributes:

  • length: It represents the length of the rectangle.
  • width: This attribute represents the width of the rectangle.

Constructors:
This class has the following constructors:
- Rectangle(): It initializes a default rectangle at (0, 0) with length = 1 and width = 1.
- Rectangle(double x, double y, double length, double width): It initializes a rectangle at (x, y) with specified dimensions.

Methods:
- area(): This constructor calculates the area using the formula length * width.
- toString(): This constructor overrides toString() to include additional rectangle attributes which are coordinates, length, width, area.


3. Parallelogram Class

image.png

  • This new class Parallelogram is inherited from Rectangle and adds a new attribute whcih is height. It represents a parallelogram in 2D space.

Attributes:
It has only one attribute which is given below:

  • height: Height of the parallelogram.

Constructors:
It has the following constructors:
- Parallelogram(): This constructor initializes a default parallelogram at (0, 0) with default dimensions.
- Parallelogram(double x, double y, double length, double width, double height): This constructor initializes a parallelogram with all the attributes.

Methods:

  • area(): This constructor overrides the area() of the Rectangle to use length * height which will be used for the parallelogram area formula.
  • volume(): This constructor calculates volume by assuming a 3D parallelogram. It uses the formula length * width * height.
  • toString(): This methdo overrides toString() method of the Rectangle to include height, area and volume.

4. GeometricInheritance Class - Test Class

This is the driver class that tests the functionality of Point, Rectangle and Parallelogram.

  1. Creating a Point:
    image.png

    • Point point = new Point(2, 3);
    • A point is created at coordinates (2, 3).
    • The toString() method displays: Point(x=2.0, y=3.0).
  2. Creating a Rectangle:
    image.png

    • Rectangle rectangle = new Rectangle(5, 6, 10, 4);
    • A rectangle is created at coordinates (5, 6) with length=10 and width=4.
    • Area is calculated as 10 * 4 = 40.
    • The toString() method displays:
  3. Creating a Parallelogram:
    image.png

    • Parallelogram parallelogram = new Parallelogram(1, 2, 8, 3, 6);
    • A parallelogram is created at (1, 2) with length=8, width=3, and height=6.
    • Area is calculated using the formula length * height = 8 * 6 = 48.
    • Volume is calculated as length * width * height = 8 * 3 * 6 = 144.
    • The toString() method displays:
      Parallelogram at Rectangle at Point(x=1.0, y=2.0), length=8.0, width=3.0, area=48.0, volume=144.0
  4. Updating the Parallelogram:
    image.png

    • The parallelogram’s height, length, and width are updated using setters.
    • New values:
      • height=10
      • length=12
      • width=5
    • Area is recalculated: length * height = 12 * 10 = 120.
    • Volume is recalculated: length * width * height = 12 * 5 * 10 = 600.

geometricInhertance-ezgif.com-optimize.gif

image.png

This demonstrates how objects of Point, Rectangle and Parallelogram behave and how they interact with each other via inheritance and overridden methods.

OOP Features Used

  1. Encapsulation:
    • Attributes are private, accessed through getters and setters.
  2. Inheritance:
    • Rectangle inherits from Point, and Parallelogram inherits from Rectangle.
  3. Method Overriding:
    • area() and toString() are overridden in child classes to provide specific functionality.
  4. Polymorphism:
    • Rectangle and Parallelogram override the parent class methods, adapting functionality.
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
Loading...