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:
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:
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
This is the base class Person
and its details are given below:
Attributes:
name
andage
are private attributes of thisPerson
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()
acceptsname
andage
as parameters to initialize the attributes when aPerson
object is created.
Methods:
displayDetails()
: This method prints thename
andage
attributes.- These methods provide the basic functionality for a
Person
.
2. Derived Class: Student
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 thePerson
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 toStudent
.
Constructor:
- The constructor of the class
Student
usessuper(name, age)
to call the parent class (Person
) constructor. This initializesname
andage
in the base class. - Then it initializes the
studentId
attribute within theStudent
class.
Method Overriding:
- The
displayDetails()
method is overridden to include thestudentId
in addition to thename
andage
from the parent class. super.displayDetails()
ensures that the original functionality fromPerson
class is preserved.
3. Main Class: Inheritance
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 nameperson
.It is created using its constructor and displays its details usingdisplayDetails()
. - Then to access the
Student
class its object (student
) is created. This calls theStudent
constructor which in turn calls thePerson
constructor viasuper()
. - When
displayDetails()
is called on thestudent
object then the overridden version in theStudent
class is executed. This demonstrates method overriding.
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:
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 booleanisTriangle
to ensure that this method is specially for the triangles.
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.
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.
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
:
- 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
:
- This derived class from the
Bank
class overridesgetInterestRate()
method from the base class and it returns 3.5%.
CurrentBank
:
- 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:
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
andCurrentBank
and called their respectivegetInterestRate()
methods to display the specific rates.
- 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.
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.
Here is the implementation of the code and the explanation how it demonstrates polymorphism in action:
Base Class (Vehicle
)
- 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
)
- Both
Bike
andTruck
extend theVehicle
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
- Polymorphism allows a parent class reference (
Vehicle
) to refer to objects of derived classes (Bike
andTruck
). - 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 aVehicle
reference the overridden method in the derived class (Bike
orTruck
) is executed.
How Polymorphism Works Here
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.
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.
- The base class (
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.
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
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()
: UpdatesisAvailable
tofalse
and provides feedback.returnItem()
: UpdatesisAvailable
totrue
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
- 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
- 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
This class contains the main logic of the program including the menu driven interface and methods for user operations.
Features
Library Initialization (initializeLibrary
)
- 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
)
- Iterates over the
libraryItems
list and calls thedisplayDetails()
method for each item. - Demonstrates polymorphism as the appropriate
displayDetails()
method (fromBook
orMagazine
) is called dynamically.
Borrow Item (borrowItem
)
- 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
)
- Similar to
borrowItem
, but it calls thereturnItem()
method to mark the item as available.
Add Item (addItem
)
- Allows users to add new
Book
orMagazine
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.
Key Concepts
Inheritance
- The
Book
andMagazine
classes inherit attributes (id
,title
,isAvailable
) and methods (borrowItem
,returnItem
,displayDetails
) from theItem
class.
Polymorphism
- The
displayDetails
method is overridden in the derived classes to provide specific details for books and magazines. - The
libraryItems
list is of typeItem
. When callingdisplayDetails()
, the method of the actual object's class (Book
orMagazine
) is invoked dynamically.
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.
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
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 to0.0
.
Constructor:
- There is a constructor of the
Employee
class and this constructor initializesname
,CIN
andaddress
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
:
- Represents employees with a fixed monthly salary.
Attributes:monthlySalary
: Stores the fixed monthly salary.
calculateSalary()
:- Assigns
monthlySalary
to thesalary
attribute.
display()
: - Calls the base class
display()
method to print employee details and salary.
PermanentEmployee
:
- 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
andperformanceBonus
.
display()
: - Calls the base class
display()
method, appending additional details for permanent employees.
HourlyWorker
:
- 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
byhourlyRate
.
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.
- The program uses a
Vector<Employee>
to store objects of different employee types such asContractualEmployee
,PermanentEmployee
andHourlyWorker
. - 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.
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
extendsC1
so it is a subclass ofC1
.C111
extendsC11
so it is a subclass ofC11
and by inheritance it is also a subclass ofC1
.
Instructions:
Instruction 1:
o1 = o2;
- Valid.
o2
is aC11
object, andC1 o1
can reference aC11
object becauseC11
is a subclass ofC1
.
- Valid.
Instruction 2:
o1 = o3;
- Valid.
o3
is of typeC111
, ando1
is of typeC1
, so a reference to aC111
object can be assigned to aC1
reference, sinceC111
is a subclass ofC1
.
- Valid.
Instruction 3:
o3 = o1;
- Invalid (Compilation error).
o1
is of typeC1
, buto3
is of typeC111
. You cannot assign aC1
object to aC111
reference unless you know for sure thato1
refers to aC111
object (which cannot be guaranteed here). This causes a compilation error.
- Invalid (Compilation error).
Instruction 4:
o4 = o5;
- Valid.
o5
is of typeC1
, ando4
is of typeC11
. SinceC11
is a subclass ofC1
, assigningo5
(of typeC1
) too4
(of typeC11
) is valid, as long as the object referenced byo5
is of typeC11
or its subclass (which is the case witho5
referring to aC111
object).
- Valid.
Instruction 5:
o3 = (C111) o1;
- Invalid (Runtime error).
o1
is of typeC1
, but it doesn't necessarily refer to aC111
object (it could refer to any object of typeC1
). Trying to cast aC1
object toC111
will result in aClassCastException
at runtime ifo1
is not actually an instance ofC111
.
- Invalid (Runtime error).
Instruction 6:
o4 = (C11) o5;
- Valid.
o5
is of typeC1
, but sinceo4
is of typeC11
, andC11
is a subclass ofC1
, castingo5
toC11
is valid. This cast will succeed at runtime ifo5
refers to aC11
orC111
object.
- Valid.
Instruction 7:
o4 = (C111) o2;
- Invalid (Runtime error).
o2
is of typeC11
, but casting it toC111
will fail at runtime ifo2
is not an instance ofC111
. Sinceo2
is aC11
, this cast will throw aClassCastException
at runtime ifo2
is not actually aC111
object.
- Invalid (Runtime error).
Instruction 8:
o3 = (C11) o5;
- Invalid (Runtime error).
o5
is of typeC1
, but casting it toC11
and assigning it too3
(which is of typeC111
) will result in a runtime error if the object referenced byo5
is not an instance ofC111
. The cast will succeed only ifo5
refers to aC111
object, and even then, assigning it to aC111
reference is invalid because it is being cast toC11
.
- Invalid (Runtime error).
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
- This
Point
class represents a point in a 2D space withx
(abscissa) andy
(ordinate) coordinates.
Attributes:
- It has attributes
x
andy
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
- This class is inherited from
Point
. It represent a rectangle in a 2D space. It adds two new attributes:length
andwidth
. - *For the inheritance it uses the
super
keyword to call the constructor of the parent classPoint
to initializex
andy
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
- This new class
Parallelogram
is inherited fromRectangle
and adds a new attribute whcih isheight
. 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 theRectangle
to uselength * 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 theRectangle
to includeheight
,area
andvolume
.
4. GeometricInheritance Class - Test Class
This is the driver class that tests the functionality of Point
, Rectangle
and Parallelogram
.
Creating a Point:
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)
.
Creating a Rectangle:
Rectangle rectangle = new Rectangle(5, 6, 10, 4);
- A rectangle is created at coordinates
(5, 6)
withlength=10
andwidth=4
. - Area is calculated as
10 * 4 = 40
. - The
toString()
method displays:
Creating a Parallelogram:
Parallelogram parallelogram = new Parallelogram(1, 2, 8, 3, 6);
- A parallelogram is created at
(1, 2)
withlength=8
,width=3
, andheight=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
Updating the Parallelogram:
- The parallelogram’s
height
,length
, andwidth
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
.
- The parallelogram’s
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
- Encapsulation:
- Attributes are private, accessed through getters and setters.
- Inheritance:
Rectangle
inherits fromPoint
, andParallelogram
inherits fromRectangle
.
- Method Overriding:
area()
andtoString()
are overridden in child classes to provide specific functionality.
- Polymorphism:
Rectangle
andParallelogram
override the parent class methods, adapting functionality.