Oop Lab Manual (Mids)
Oop Lab Manual (Mids)
Lab Manual
Department: __________________________________
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
CONTENTS
Lab Total Page #
. Date List of Experiment Mark Signature
No. s
Objectives:
Getting familiar with the
Java development kit (JDK).
Running your first Java
program using CMD and an
1. IDE.
Learning Input/Output
handling on Java console.
Understanding variables
using primitive and non-
primitive data types.
Exploring Java’s built-in
classes.
Objective: Understanding
variables using primitive and non-
2.
primitive data types, control
statements of Java including
Loops & if-else. Exploring different
operators used in Java.
Objectives:
Understanding concepts of
class and object in java.
Implementing a class with
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
members including data,
methods and constructors.
Understand the basics of
UML class diagrams.
Objectives:
Understanding concepts
method and constructor
overloading. Learn how to
4. provide different access
controls on class members.
Interpret UML class
diagrams to model
overloaded methods and
access control.
Objectives:
Understanding the concept
of inheritance, the
superclass and subclass.
Understand the abstract
method & class and final
method and class.
Interpret UML class
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
diagrams to
model inheritance and
abstraction.
Objectives:
Understanding the concept
9 packages & interfaces of
Java.
Interpret UML class
diagrams to model
inheritance and abstraction
Exception Handling
10. Objective: Understand how
runtime errors are being handled
in Java.
Introducing JavaFX – Java GUI
Final Examination
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
Lab Session 1
Objective:
a) Getting familiar with the Java development kit (JDK). Running your first Java program using
CMD and an IDE.
b) To learn Input/output handling on Java console. Understanding variables using primitive and non-
primitive data types. Exploring Java’s built-in classes.
Introduction:
What is JDK?
It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools
(like Java Debugger) to create and compile programs.
JRE is required to run Java programs while JDK is required when you have to do some Java
programming.
Required IDE:
1
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
2
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
3
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
4
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
5
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
1. Install IDE: Ensure that your IDE is installed and configured properly with JDK (Java
Development Kit).
2. Download Eclipse form its official website and install it on your system by following the
instruction provided by the installer.
6
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
7
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
8
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
9
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
10
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
System.in to the standard input device. Console input is not directly supported in Java,
but Scanner class is used to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();
Console output
Java uses System.out to refer to the standard output device.To perform console output,
println method is used to display a primitive value or a string to the console.
System.out.print("Hello ");
System.out.println("world");
You can use the System.out.printf method to display formatted output on the console.
System.out.printf(“Your Total amount is %4.2f", total);
System.out.printf("count is %d and amount is %f", +count, amount);
11
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
1. Primitive
A primitive type is predefined by the language and is named by a reserved
keyword.
2. Non-Primitive
It is a reference data type, which are references to objects.
System.out.println((int)1.7);
The above statement displays 1. When a double value is cast into an int value, the
fractional part is truncated.
Math
Math class file is included for the definitions of math functions listed below. It is
written as java.lang.Math.
12
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
● tan(n) ● pow(nmb,pwr)
● sinh(n) ● sqrt(n)
Date
snh=Math.sinh(b);
csh=Math.cosh(b);
tnh=Math.tanh(b);
System.out.println("\nTrignometric Functions");
System.out.println("sin 45 = " + sn);
System.out.println("cos 45 =" + cs);
System.out.println("tan 45 =" + tn);
System.out.println("\nHyperbolic Functions");
System.out.println("sinh 1 = " + snh);
System.out.println("cosh 1 = " + csh);
System.out.println("tanh 1 = " + tnh);
Expected Outcome:
13
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
Task #1
14
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
Scenario: You are building a simple Java console application that asks the user for their first
name, last name, and age. Once the user provides the input, the program should display a
welcome message that includes their full name and their age in 5 years.
Task Description:
Write a Java program that handles user input from the console for first name, last name, and age.
Then, output a welcome message that includes their full name and calculates their age in 5 years.
Task #2
15
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
Scenario: Create a basic program for a fitness tracking app that computes the total distance a
person runs in a week. The app keeps track of the distance the user runs each day, from Monday
to Sunday.
1. Define seven variables (of type double) to hold the distance the user runs for each day of
the week: monday, tuesday, wednesday, thursday, friday, saturday, and sunday.
2. Declare another variable, totalDistance, to store the total distance run over the week.
3. Ask the user to input the distance they ran each day and save the input in the
corresponding variables.
4. The total distance run for the week will be calculated by adding up all the daily distances
and saving it in totalDistance.
5. Show the total distance to the user.
Task Description: Develop a fitness tracking app that computes the total distance a person runs
over a week by storing daily running distances in seven variables (double type) for each day
from Monday to Sunday. Prompt the user for the daily inputs and calculate the total distance by
summing up all the daily distances. Display the total distance to the user at the end of the
program.
Task #3
16
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
Scenario: You are working on an e-commerce platform that needs a feature to calculate
discounts on products and display the current date of the transaction.
Task Description: Create a program that takes the product's original price, applies a discount
percentage, and calculates the final price after the discount. The program should also display the
current date and time of the transaction.
Conclusion:
17
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
Lab Session 2
Objective:
To understand Java control statements, including loops and if-else structures, and to explore
various operators.
Required Tools:
Eclipse
JDK (Java Development Kit)
Introduction:
In this lab, we will focus on Java control statements which allow for decision-making and
repetition in code. Control statements like if-else, switch, and loops (for, while, do-while) are
integral in controlling the program's flow. Along with control statements, operators like
arithmetic, relational, logical, and bitwise will also be explored. Through practical tasks, we will
reinforce the theoretical knowledge of control structures and operators.
1. If-Else Structure
o Allows conditional execution of code blocks.
o Syntax:
if (condition) {
// code executed if condition is true
} else {
// code executed if condition is false
}
2. Switch Case
o An alternative to the if-else-if ladder, used when there are multiple possible
values for a single variable.
o Syntax:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
3
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
// code for no matches
}
3. Loops
o For Loop: Executes a block of code a specific number of times.
while (condition) {
// code to be repeated
}
o Do-While Loop: Executes the block at least once before checking the condition.
do {
// code to be repeated
} while (condition);
Procedure:
Write a Java program that takes the current month as an integer (1 for January, 12 for December)
and prints the corresponding season. Use an if-else-if ladder.
import java.util.Scanner;
4
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
} else {
System.out.println("Invalid month entered.");
}
}
}
2. Generate a Number Pattern using Nested Loops
Create a Java program to generate the following pattern using nested loops:
1
12
123
1234
12345
java
Copy code
public class NumberPattern {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
import java.util.Scanner;
5
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
first = second;
second = next;
}
}
}
4. Prime Number Finder
import java.util.Scanner;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
6
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
Expected Outcome:
Task #1
Scenario: You are developing a Java program that takes a user's input for their exam score and
determines if they passed or failed. The passing score is 50 or above. Based on the score, the
program should output either "Pass" or "Fail."
Task Description:
Write a Java program that takes an exam score as input and uses an if-else structure with
comparison operators to determine if the user passed or failed. Display an appropriate message
based on the result.
7
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
Task #2
Scenario: You are tasked with creating a Java program that calculates the sum of all even
numbers between 1 and 100. The program should use a loop structure to iterate through the
numbers and add the even ones to a running total.
Task Description:
Write a Java program using a loop and arithmetic operators to calculate and print the sum of all
even numbers from 1 to 100.
8
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
Task #3
Scenario: You are developing a weather prediction system that advises users on how to dress
based on the temperature and weather conditions. The system will provide recommendations
based on the temperature (in degrees Celsius) and whether it is raining or sunny.
Instructions:
1. Prompt the user to enter the current temperature (as an integer) and whether it is raining
or sunny (as a string, either "rainy" or "sunny").
2. Based on the temperature and weather conditions, the system should give advice
according to the following logic:
o If the temperature is below 0°C:
If it's raining, suggest: "Wear a heavy coat and take an umbrella."
If it's sunny, suggest: "Wear a heavy coat and sunglasses."
o If the temperature is between 0°C and 10°C:
If it's raining, suggest: "Wear a warm jacket and take an umbrella."
If it's sunny, suggest: "Wear a warm jacket and sunglasses."
o If the temperature is between 11°C and 20°C:
If it's raining, suggest: "Wear a light jacket and take an umbrella."
If it's sunny, suggest: "Wear a light jacket and sunglasses."
o If the temperature is above 20°C:
If it's raining, suggest: "Wear light clothing and take an umbrella."
If it's sunny, suggest: "Wear light clothing and sunglasses."
3. Use if-else if statements to implement this logic.
4. After processing the input, display the appropriate advice to the user.
Task Description:
You are building a weather prediction system that suggests what to wear based on the temperature and
weather (rainy or sunny). The program asks the user to input the current temperature and weather
condition, and then it gives advice on appropriate clothing. The recommendations change depending on
whether it's cold or warm and if it's rainy or sunny.
9
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
10
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
Conclusion:
11
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Lab Session 3
Objective:
Understanding concepts of class and object in Java. Implementing a class with members
including data, methods, and constructors.
Eclipse
JDK (Java Development Kit)
Introduction:
Class: A class is a blueprint or template for creating objects. It defines the attributes (data) and
behaviors (methods or functions) that the objects created from the class will have.
Objects in Java:
An object is an instance of a class. It represents a specific entity that has the properties and behaviors
defined by its class.
Procedure:
The following code demonstrates the creation of a Box class with methods and a demo class to
calculate the volume of boxes.
5
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
2. Adding Constructor
Now, we will add a constructor to the Box class that initializes the box dimensions to default
values.
class Box {
double width;
double height;
double depth;
6
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
// Compute and return volume
double volume() {
return width * height * depth;
}
}
The class should contain default and parameterized constructors. The constructors should
print the statements:
o “Inside Default Constructor”
o “Inside Parameterized Constructor”
The class should contain the following data fields and methods:
o int square = 2;
o int cube = 3;
o calculateSquare(int x)
o calculateCube(int x)
o calculateFactorial(int x)
o generateTable(int x)
Create objects of this class using both constructors in the main class.
Call all four functions via the objects.
// Default constructor
Calculator() {
System.out.println("Inside Default Constructor");
}
// Parameterized constructor
Calculator(int x) {
System.out.println("Inside Parameterized Constructor");
}
// Calculate square
int calculateSquare(int x) {
return x * x;
7
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
}
// Calculate cube
int calculateCube(int x) {
return x * x * x;
}
// Calculate factorial
int calculateFactorial(int x) {
if (x == 0 || x == 1) {
return 1;
} else {
return x * calculateFactorial(x - 1);
}
}
// Call methods
System.out.println("Square of 4: " + calcDefault.calculateSquare(4));
System.out.println("Cube of 3: " + calcDefault.calculateCube(3));
System.out.println("Factorial of 5: " + calcDefault.calculateFactorial(5));
calcDefault.generateTable(7);
}
}
8
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Expected Outcome:
Task #1
Scenario: You are developing an online shopping cart system for an e-commerce website. Each
item added to the cart is represented as an object of the Item class. You will use constructors to
initialize the objects with the item details, such as item name, price, and quantity.
The system needs to calculate the total price of the items in the cart, display each item’s details,
and update the quantity of an item if more units are added.
Requirements:
1. Item Class: This class will represent the items that the user can add to the cart. Each item
has:
o name: The name of the item (String)
o price: The price of the item (double)
o quantity: The quantity of the item added to the cart (int)
2. Constructor: The Item class will use a constructor to initialize the attributes name, price,
and quantity when a new item is added to the cart.
3. Methods:
o A method getTotalPrice() that calculates and returns the total price of the item based on its
quantity and price.
o A method displayItemDetails() to display the item's details (name, price, quantity, and total
price).
o A method updateQuantity() to update the quantity of the item if more units are added.
9
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Task Description: You are building an online shopping cart system where each product in the
cart is represented as an item. The system uses a class called Item to store details like the item’s
name, price, and quantity. A constructor initializes these values when a new item is added to the
cart. The system can calculate the total price for each item, display the item’s details, and update
the quantity if more units of the item are added.
10
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Task #2
11
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Scenario: You need to create a Student class for a school application. The class should have the
following attributes:
String name
int rollNumber
double[] grades
Implement a constructor to initialize name and rollNumber, and create a method to calculate the
average grade. Additionally, create a method to display the student’s details along with their
average grade.
Task Description: What would be the implementation of the Student class, and how would you
create instances of this class to track multiple students' grades?
12
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
Task #3
Scenario: You are tasked with designing a Car class for a car showroom application. The class
should include:
String make
String model
int year
double price
Implement a constructor that takes parameters for all these attributes. Add methods to:
Task Description: How would you define the Car class and utilize it in a main method to
showcase different car objects and their functionalities?
Conclusion:
13
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Lab Session 4
Objective:
Eclipse
JDK (Java Development Kit)
Introduction:
Method Overloading
Method Overloading occurs when multiple methods in a class share the same name but differ in
the number or type of parameters. It allows methods to behave differently depending on the
argument list.
Constructor Overloading
Access Control
In Java, access control defines the visibility and accessibility of class members (fields, methods,
constructors). There are four types:
Procedure:
We will create a class OverloadDemo that demonstrates method overloading by having several
methods named test but with different parameters.
7
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
class OverloadDemo {
// Method with no parameters
void test() {
System.out.println("No parameters");
}
// No-arg constructor
OverloadDemo() {
System.out.println("No-args constructor");
}
// Parameterized constructor
OverloadDemo(int demo) {
System.out.println("Parameterized Constructor: " + demo);
}
}
class Overload {
public static void main(String[] args) {
OverloadDemo ob = new OverloadDemo(); // Default constructor
OverloadDemo ob1 = new OverloadDemo(33); // Parameterized constructor
double result;
// Call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
8
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
2. Account Class Implementation
We will implement the Account class with private data members and provide overloaded
constructors, accessor, and mutator methods. We will also implement methods to calculate the
monthly interest and modify the balance.
import java.util.Date;
class Account {
private int id;
private double balance;
private static double annualInterestRate;
private Date dateCreated;
// No-arg constructor
public Account() {
this.id = 0;
this.balance = 0;
this.dateCreated = new Date();
}
// Parameterized constructor
public Account(int id, double balance) {
this.id = id;
this.balance = balance;
this.dateCreated = new Date();
}
9
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
// Getter and setter for annualInterestRate
public static double getAnnualInterestRate() {
return annualInterestRate;
}
class AccountDemo {
public static void main(String[] args) {
// Create an Account object
Account account = new Account(1122, 20000);
Account.setAnnualInterestRate(4.5);
10
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Expected Outcome:
Task #1
11
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Scenario: You are developing a simple payment system for an e-commerce application. Create a
class PaymentProcessor that processes payments in different ways:
Task Description: How would you implement the PaymentProcessor class with method
overloading, and how would you call each overloaded method in the main class?
12
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Task #2
You are designing a Library Management System that keeps track of books in a library. The
system uses a Book class that represents the books available. To manage different types of books,
you will implement constructor overloading within the Book class to allow for various ways of
creating book objects based on different parameters.
Requirements:
1. Book Class: This class will represent the books in the library with the following
attributes:
o title: The title of the book (String)
o author: The author of the book (String)
o ISBN: The International Standard Book Number (String)
o yearPublished: The year the book was published (int)
o copiesAvailable: The number of copies available in the library (int)
2. Constructor Overloading: The Book class will have multiple constructors to initialize
the objects in different ways:
o A constructor that takes only the title and author.
o A constructor that takes the title, author, and ISBN.
o A constructor that takes all attributes: title, author, ISBN, yearPublished, and
copiesAvailable.
3. Methods:
o A method displayBookInfo() to display the details of the book.
o A method updateCopies(int newCopies) to update the number of available
copies.
Task Description: You are creating a Library Management System using a Book class that can
be initialized in multiple ways through constructor overloading. You can create a book with just
the title and author, or include the ISBN, or provide all details like year published and available
copies. The system includes methods to display book details and update the number of available
copies, allowing for flexible management of library books.
13
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
14
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Task #3
You are tasked with designing an Online Course Management System for a university. The
system will handle information about various courses and instructors. You will need to
implement classes that utilize protected and private variables, along with constructor
overloading and method overriding.
1. Classes:
o Course Class: This class should have the following attributes:
courseName (private): The name of the course.
courseID (private): A unique identifier for the course.
credits (protected): The number of credits the course offers.
o Instructor Class: This class should inherit from the Course class and have the following
attributes:
instructorName (private): The name of the instructor.
department (protected): The department the instructor belongs to.
2. Constructor Overloading:
o The Course class should have multiple constructors:
One constructor that takes only courseName and courseID.
Another constructor that takes courseName, courseID, and credits.
o The Instructor class should also have overloaded constructors:
One that takes only instructorName and department.
Another that takes instructorName, department, and an instance of
Course to associate the instructor with a course.
3. Method Overriding:
o Both classes should include a method called getDetails():
The Course class’s getDetails() method should return the course name and
ID.
The Instructor class’s getDetails() method should override this to return
the instructor’s name and associated course details.
Task Description: You are designing an Online Course Management System with two classes:
Course and Instructor.
The Course class has private attributes for courseName and courseID, and a protected
attribute for credits. It features overloaded constructors for different initialization
options and a getDetails() method to display course information.
The Instructor class inherits from the Course class, adding a private instructorName
and a protected department. It also includes overloaded constructors and overrides the
getDetails() method to show both instructor and associated course details.
The goal is to implement these classes in Java and create instances to verify the system's
functionality.
15
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
16
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
17
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
Conclusion:
18
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
Lab Session 5
Objective:
The objective of this lab is to understand the concept of arrays (both single and multi-
dimensional), array indexing, and how to traverse arrays using loops. Additionally, we aim to
become familiar with the String class in Java and explore various operations such as comparison,
extraction, and manipulation of strings.
Eclipse
JDK (Java Development Kit)
Introduction:
Arrays
An array in Java is a fixed-size, sequential collection of elements of the same type. Once an array
is created, its size cannot be changed. The array elements are accessed using an index, which
starts from 0.
Syntax:
To assign values:
Strings in Java
In Java, strings are represented as objects. The String class is immutable, which means once a
string object is created, it cannot be modified.
Syntax:
9
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
2. equalsIgnoreCase(StringLiteral): Compares strings ignoring case differences.
3. compareTo(StringLiteral): Compares two strings lexicographically.
Procedure:
Write a program using a one-dimensional array to find the average of a set of numbers.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
for (int i = 0; i < nums.length; i++) {
result += nums[i];
}
System.out.println("Average is " + result / nums.length);
}
}
2. Initialize 2D Array with Random Numbers
Write a program to initialize and print a 5x5 2D array with random numbers.
class RandomArray2D {
public static void main(String[] args) {
double[][] array2d = new double[5][5];
for (int row = 0; row < array2d.length; row++) {
for (int col = 0; col < array2d[row].length; col++) {
array2d[row][col] = Math.round(Math.random() * 100);
}
}
for (int row = 0; row < array2d.length; row++) {
for (int col = 0; col < array2d[row].length; col++) {
System.out.print(array2d[row][col] + " ");
}
System.out.println();
}
}
}
3. Explore String Methods
Write a program to explore different methods of the String class, such as equals,
equalsIgnoreCase, and getChars.
class GetCharsDemo {
public static void main(String args[]) {
10
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
String longStr = "This could have been a very long line...";
System.out.println(longStr);
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Goodbye";
String s4 = "HELLO";
Expected Outcome:
11
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
Task #1
Scenario:
You are developing a program to help a weather monitoring system analyze temperature data for
a city. The system collects daily temperature readings for 7 days, and you are required to
generate a summary report based on this data.
Task Description:
12
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
Task #2
Scenario:
You are working on an inventory management system for a retail store chain. The system keeps
track of the stock levels for multiple products across several branches. The stock levels are stored
in a 2D array, where each row represents a product and each column represents a branch.
Task Description:
Initializes a 2D array (with 5 products and 4 branches) with random stock levels between
0 and 100.
Traverses the 2D array using nested loops to display the stock count for each product at
each branch.
Calculates the total stock of each product across all branches and identifies the product
with the highest stock.
13
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
Task #3
Scenario:
You are building a customer service application that needs to identify potential duplicate
customer records in a list. The list contains customer names, and duplicates may appear with
different capitalization (e.g., "John" and "john").
Task Description:
14
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering
Conclusion:
15
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Lab Session 6
Objective:
The objective of this lab session is to understand the concept of inheritance, including superclass
and subclass relationships in Java, and how it promotes code reuse and specialization in object-
oriented programming through the implementation of various classes and methods. Additionally,
the lab focuses on abstract methods and classes, as well as final methods and classes in Java,
highlighting how these concepts facilitate a structured approach to object-oriented programming,
with an open-ended lab component to encourage exploration and practical application.
Eclipse
JDK (Java Development Kit)
Introduction:
Procedure:
1. Inheritance Basics
This task demonstrates basic inheritance by creating a Box class and extending it with a
BoxWeight class.
11
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
// construct clone of an object
Box(Box ob) {
width = ob.width;
height = ob.height;
depth = ob.depth;
}
12
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Expected Output
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
2. Multilevel Inheritance
This task demonstrates multilevel inheritance by extending BoxWeight with a Shipment class
that adds a cost attribute.
// default constructor
Shipment() {
13
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
super();
cost = -1;
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is " + shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is " + shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Expected Output
swift
Copy code
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
14
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
3. Lab Assignment
In this task, we will design a class hierarchy involving Person, Student, Employee, Faculty, and
Staff.
class Person {
String name, address, phoneNumber, email;
Student(String name, String address, String phoneNumber, String email, String status) {
super(name, address, phoneNumber, email);
this.status = status;
}
Employee(String name, String address, String phoneNumber, String email, String office,
double salary, String dateHired) {
super(name, address, phoneNumber, email);
this.office = office;
this.salary = salary;
this.dateHired = dateHired;
}
15
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
public String toString() {
return "Employee: " + name;
}
}
Faculty(String name, String address, String phoneNumber, String email, String office, double
salary, String dateHired, String officeHours, String rank) {
super(name, address, phoneNumber, email, office, salary, dateHired);
this.officeHours = officeHours;
this.rank = rank;
}
Staff(String name, String address, String phoneNumber, String email, String office, double
salary, String dateHired, String title) {
super(name, address, phoneNumber, email, office, salary, dateHired);
this.title = title;
}
16
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
System.out.println(person.toString());
System.out.println(student.toString());
System.out.println(employee.toString());
System.out.println(faculty.toString());
System.out.println(staff.toString());
}
}
17
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Expected Outcome:
18
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Task #1
You have been assigned the responsibility of designing a Fleet Management System for a
transportation company that manages various vehicle types, specifically Sedans and Cargo
Trucks. This system must leverage the principles of inheritance, constructor overloading, and
method overriding to efficiently handle the specifications and operations of each vehicle type.
2. Derived Classes:
o Sedan Class:
Inherit from the Vehicle class.
Introduce a private attribute numberOfDoors (int): indicating how many
doors the sedan has.
Provide a constructor that initializes the manufacturer, model,
manufacturingYear, and numberOfDoors.
Override the displayDetails() method to include the number of doors in the
output.
o CargoTruck Class:
Inherit from the Vehicle class.
Add a private attribute cargoCapacity (double): representing the maximum
weight the truck can carry.
Provide a constructor that initializes the manufacturer, model,
manufacturingYear, and cargoCapacity.
Override the displayDetails() method to present the cargo capacity
alongside the other vehicle details.
Task Description:
In the Fleet Management System for a transportation company, a base class named Vehicle is
created with private attributes for the manufacturer and model, and a protected attribute for the
manufacturing year. Two derived classes, Sedan and CargoTruck, inherit from the Vehicle class.
19
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
The Sedan class includes an additional private attribute for the number of doors, while the
CargoTruck class features a private attribute for cargo capacity. Each derived class has its own
constructor to initialize all attributes and overrides the displayDetails() method to present
specific information. This scenario showcases the principles of inheritance, constructor
overloading, and method overriding in object-oriented programming.
20
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Task #2
Scenario:
An academic institution needs to manage the hierarchy of its employees, which includes general
staff, faculty, and administrators. Each employee has a salary, but faculty members also have
office hours and a rank. The system needs to keep track of these attributes and allow for
customized printing of details based on the type of employee.
Task Description:
1. Create a base class Person with fields for name, address, phone number, and email
address.
2. Extend Person to create an Employee class with fields for salary and the date of hiring.
3. Further extend Employee to create a Faculty class that adds fields for office hours and
rank.
4. Override the toString() method in each class to output customized details for each type of
person.
5. Write a main program to create objects for a generic person, employee, and faculty
member, then print their details using the overridden toString() methods.
21
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Task #3
Scenario:
A company needs to track shipments of products, which have multiple layers of attributes such
as size, weight, and shipping costs. The system must calculate the volume, weight, and total cost
of shipping a product based on its attributes.
Task Description:
1. Create a Box class with width, height, and depth, along with a method to calculate the
volume.
2. Extend Box to a BoxWeight class, which adds a weight attribute.
3. Extend BoxWeight into a Shipment class, which adds a cost attribute for shipping.
4. Write a main program that creates shipment objects, calculates and displays their volume,
weight, and shipping cost.
22
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
Conclusion:
23
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
Introduction:
Inheritance is a key principle of object-oriented programming that allows one class (subclass) to
inherit properties and behaviors (fields and methods) from another class (superclass). This
facilitates the creation of hierarchical structures, enabling general attributes and methods to be
defined in a superclass and inherited by more specific subclasses. Key concepts include:
Procedure:
2. Implement a Subclass:
o Create a SavingsAccount class that extends Account and implements the
withdrawal and deposit methods with the specified conditions.
13
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
class SavingsAccount extends Account {
public SavingsAccount(String id, double initialDeposit) {
super(id, initialDeposit >= 10 ? initialDeposit : throw new
IllegalArgumentException("Initial deposit must be at least $10"));
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public boolean withdraw(double amount) {
if (balance - amount - 2 < 10) {
return false; // Insufficient funds after withdrawal fee
}
balance -= amount + 2; // Deduct the transaction fee
return true; // Withdrawal successful
}
}
14
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
2. Test Final Class:
o Attempt to extend the final class to demonstrate that it cannot be inherited.
Expected Outcome:
Task #1
Scenario:
A banking application needs to manage different types of accounts, including savings and
checking accounts. The system should ensure that all accounts can perform common operations
such as deposits and withdrawals, while also allowing for specific implementations based on the
type of account.
Task Description:
15
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
public Account(String id, double balance): A constructor that initializes
the account ID and balance.
public String getID(): Returns the account ID.
public double getBalance(): Returns the current balance.
public abstract boolean withdraw(double amount): An abstract method for
withdrawing money.
public abstract void deposit(double amount): An abstract method for
depositing money.
2. Create Subclass:
o Implement a subclass named SavingsAccount that extends Account and includes:
A constructor that requires an initial deposit of at least $10.
Implementation of the withdraw method, including a transaction fee of $2
for each withdrawal, ensuring that the balance does not drop below $10
after withdrawal.
16
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
17
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
Task #2
Scenario:
A logistics company wants to manage the shipping of products with strict guidelines. Certain
types of boxes should not be altered or inherited further, as they represent standardized shipping
containers.
Task Description:
2. Prevent Inheritance:
o Ensure that ShippingBox cannot be inherited by any other class.
3. Demonstrate Functionality:
o Write a main method that creates an instance of ShippingBox, calculates its
volume, and displays the result. Attempting to extend ShippingBox in another
class should result in a compile-time error.
18
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
19
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
Task #3
Scenario:
An educational institution needs to manage various staff roles, including faculty and
administrative personnel. It requires a system that distinguishes between different types of
employees while enforcing specific rules about roles and responsibilities.
Task Description:
3. Implement Subclasses:
o Create two subclasses: Faculty and Staff, which inherit from Employee and
implement the getDetails() method to return customized details specific to their
roles.
20
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
21
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
22
Object Oriented Programming ______ Lab Session 6
Iqra University Department of Computer Science
Conclusion:
23