[go: up one dir, main page]

0% found this document useful (0 votes)
22 views83 pages

Oop Lab Manual (Mids)

Uploaded by

Abdullah Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views83 pages

Oop Lab Manual (Mids)

Uploaded by

Abdullah Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Department of Computer Science

Lab Manual

Object Oriented Programming

Instructor’s Name: ____________________________

Student’s Name: ______________________________

Roll No.: ______________ Batch: ________________

Semester: ______________ Year: _________________

Department: __________________________________
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
CONTENTS
Lab Total Page #
. Date List of Experiment Mark Signature
No. s

Introduction to Java and


Programming Elements

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.

Java Control Statement, Loops


& Operators

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.

3. Introducing Classes and


Objects

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.

Overloading & Access Control

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.

Arrays & Strings

Objective: Understanding Arrays,


array index, single and multi-
5. dimensional arrays, traversing the
array using loop. Getting familiar
with the String class of Java.

6. Inheritance in Java, Use of


abstract and final

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.

7 Open Ended Lab

Mid Term Examination

Packages & Interfaces

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

Objective: Understand the design


principles of graphical user
interfaces (GUIs) using layout
11. managers to arrange GUI
components. Understand basic
component of JavaFX and their
interaction used in different
program of Java, such as Label,
Button, Text Box, Combo Box etc.
12. Exploring JavaFX layouts and
charts

Objective: Understand and


implement different layouts and
FACULTY OF ENGINEERING SCIENCES AND TECHNOLOGY
charts in JavaFX to enhance user
interfaces.
JavaFX Application: Design
with Event Handling
13. Objective: Design Sign up and
Login pages using JavaFX
components and implement Event
Handling.
File Handling in Java

Objective: Understand the


14. concept of file handling in Java by
implementing a signup page that
stores user information in a text
file.
15. Assessment of Open Ended
Lab

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.

Installing JDK for Windows


1. Download the JDK from Oracle’s website. Choose the right JDK depending upon your
system’s specifications.

Required IDE:

 JDK (Java Development Kit)


 Eclipse
Procedure:
Step 1: Setup the JDK:

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

Step 2: Setup the Eclipse IDE

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

Understanding Java Console Input and Output


Theory:
Console input

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();

Import the class by adding


import java.util.Scanner;

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);

Data Types in Java


A data type in a programming language is a set of data with values having predefined
characteristics.
There are two basic types in Java.

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.

Figure 2.1: Data Types in Java


Variables

Variable is a name of memory location.


It is name of reserved area allocated in memory.
In the given example; int is data type, a is variable name
and 10 is the value that a variable holds, followed by a terminator;

Figure 2.2: Variable Initialization


Type Conversion
Casting is an operation that converts a value of one data type into a value of
another data type. The syntax for casting a type is to specify the target type in
parentheses, followed by thevariable’s name or the value to be cast. For example;

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.

Some Useful Java Classes

Math
Math class file is included for the definitions of math functions listed below. It is
written as java.lang.Math.

Trignometic / Maths Functions


● sin(n) ● hosh(n)
● cos(n) ● tanh(n)

12
Object Oriented Programming ______ Lab Session 01
Iqra University Department of Software Engineering
● tan(n) ● pow(nmb,pwr)
● sinh(n) ● sqrt(n)

Date

Java provides a system-independent encapsulation of date and


time in the java.util.Date class. The no-arg constructor of the
Date class can be used to create an instance for the current
date and time.
1. Write a Java program to explore Math class.

public class MathClass


{
public static void main(String[] args)
{
double a=45,b=1,sn,cs,tn,snh,csh,tnh;
sn=Math.sin(a);
cs=Math.cos(a);
tn=Math.tan(a);

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.

Discussion and analysis of results:

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.

Java Control Statements:

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.

for (initialization; condition; increment/decrement) {


// code to be repeated
}

o While Loop: Repeats a block of code while a condition is true.

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:

1. Using if-else-if Ladder to Determine the Season

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;

public class SeasonFinder {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter month (1-12): ");
int month = input.nextInt();

if (month == 12 || month == 1 || month == 2) {


System.out.println("Season: Winter");
} else if (month >= 3 && month <= 5) {
System.out.println("Season: Spring");
} else if (month >= 6 && month <= 8) {
System.out.println("Season: Summer");
} else if (month >= 9 && month <= 11) {
System.out.println("Season: Fall");

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();
}
}
}

3. Fibonacci Sequence Generator

Write a program to generate the first n numbers in the Fibonacci sequence.

import java.util.Scanner;

public class FibonacciGenerator {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of Fibonacci numbers to generate: ");
int n = input.nextInt();

int first = 0, second = 1;


System.out.print("Fibonacci Series: " + first + ", " + second);

for (int i = 3; i <= n; i++) {


int next = first + second;
System.out.print(", " + next);

5
Object Oriented Programming ______ Lab Session 02
Iqra University Department of Software Engineering
first = second;
second = next;
}
}
}
4. Prime Number Finder

Write a Java program to check if a number is prime or not.

import java.util.Scanner;

public class PrimeChecker {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to check if it's prime: ");
int num = input.nextInt();

boolean isPrime = true;

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

Discussion and analysis of results:

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.

Required Equipment / tools:

 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.

A class consists of:

 Data (Variables): Attributes that define the properties of the class.


 Methods: Functions defined within the class that operate on the class's data.
 Constructors: Special methods that are called when an object of the class is instantiated.

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:

1. Box Class Implementation

The following code demonstrates the creation of a Box class with methods and a demo class to
calculate the volume of boxes.

// Box class definition


class Box {
double width;
double height;
double depth;

// Compute and return volume


double volume() {
return width * height * depth;
}
}

5
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering

// ___________ Demo Class ___________


class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box(); // Create first object
Box mybox2 = new Box(); // Create second object
double vol;

// Assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

// Assign different values to mybox2's instance variables


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// Get volume of first box


vol = mybox1.volume();
System.out.println("Volume of Box 1 is " + vol);

// Get volume of second box


vol = mybox2.volume();
System.out.println("Volume of Box 2 is " + vol);
}
}

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;

// This is the constructor for Box.


Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}

6
Object Oriented Programming ______ Lab Session 03
Iqra University Department of Software Engineering
// Compute and return volume
double volume() {
return width * height * depth;
}
}

3. Create a Calculator Class

Create a class Calculator with the following details:

 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.

// Calculator class definition


class Calculator {
int square = 2;
int cube = 3;

// 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);
}
}

// Generate multiplication table


void generateTable(int x) {
System.out.println("Multiplication Table of " + x + ":");
for (int i = 1; i <= 10; i++) {
System.out.println(x + " x " + i + " = " + (x * i));
}
}
}

// Main class to demonstrate Calculator


public class CalculatorDemo {
public static void main(String[] args) {
// Create object using default constructor
Calculator calcDefault = new Calculator();

// Create object using parameterized constructor


Calculator calcParam = new Calculator(5);

// 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:

 Display car details.


 Apply a discount on the car price.
 Check if the car is a classic (older than 20 years).

Task Description: How would you define the Car class and utilize it in a main method to
showcase different car objects and their functionalities?

Discussion and analysis of results:

Conclusion:

13
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering

Lab Session 4

Objective:

Understanding the concepts of method overloading, constructor overloading, and access


control in Java. Learn how to define a class with multiple methods and constructors with
different parameters and apply access controls to class members.

Required Equipment / tools:

 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

Constructor Overloading involves defining multiple constructors with different parameters in a


class, allowing objects to be instantiated in various ways.

Access Control

In Java, access control defines the visibility and accessibility of class members (fields, methods,
constructors). There are four types:

1. private: Accessible only within the class.


2. default (package-private): Accessible within the same package.
3. protected: Accessible within the same package and by subclasses.
4. public: Accessible from anywhere.

Procedure:

1. Method Overloading Demonstration

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");
}

// Overloaded method with one integer parameter


void test(int a) {
System.out.println("a: " + a);
}

// Overloaded method with two integer parameters


void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

// Overloaded method with one double parameter


double test(double a) {
System.out.println("double a: " + a);
return a * a;
}

// 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();
}

// Getter and setter for id


public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

// Getter and setter for balance


public double getBalance() {
return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

9
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering
// Getter and setter for annualInterestRate
public static double getAnnualInterestRate() {
return annualInterestRate;
}

public static void setAnnualInterestRate(double annualInterestRate) {


Account.annualInterestRate = annualInterestRate;
}

// Getter for dateCreated


public Date getDateCreated() {
return dateCreated;
}

// Method to calculate monthly interest rate


public double getMonthlyInterestRate() {
return annualInterestRate / 12;
}

// Method to calculate monthly interest


public double getMonthlyInterest() {
return balance * getMonthlyInterestRate() / 100;
}

// Method to withdraw amount from the balance


public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}

// Method to deposit amount to the balance


public void deposit(double amount) {
balance += amount;
}
}

class AccountDemo {
public static void main(String[] args) {
// Create an Account object
Account account = new Account(1122, 20000);
Account.setAnnualInterestRate(4.5);

// Withdraw and deposit


account.withdraw(2500);
account.deposit(3000);

10
Object Oriented Programming ______ Lab Session 04
Iqra University Department of Software Engineering

// Print account details


System.out.println("Balance: $" + account.getBalance());
System.out.println("Monthly Interest: $" + account.getMonthlyInterest());
System.out.println("Date Created: " + account.getDateCreated());
}
}

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:

 If no parameters are provided, it should print "Processing default payment."


 If one integer parameter is provided, it should print "Processing payment of amount
[parameter]."
 If two parameters (an integer and a string) are provided, it should print "Processing
payment of [parameter] for [customer name]."

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

Discussion and analysis of results:

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.

Required Equipment / tools:

 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:

elementType[] arrayRefVar = new elementType[arraySize]; // One-dimensional array


elementType[][] arrayRefVar; // Two-dimensional array

To assign values:

arrayRefVar[index] = value; // One-dimensional array


arrayRefVar[row][column] = value; // Two-dimensional array

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:

String newString = new String("stringLiteral");


String newString = "stringLiteral";
Common String Methods:

1. equals(StringLiteral): Compares two strings for equality.

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:

1. Calculate Average of an Array

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 s = "This is a demo of the getChars method.";


int start = 10, end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);

String s1 = "Hello";
String s2 = "Hello";
String s3 = "Goodbye";
String s4 = "HELLO";

System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));


System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
}
}

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:

Write a Java program that:

 Uses a one-dimensional array to store the temperature readings for 7 days.


 Calculates and displays the average temperature for the week.
 Identifies and prints the highest and lowest temperatures recorded.
 Traverses the array using a loop to print the temperature readings for each day.

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:

Write a Java program that:

 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:

Write a Java program that:

 Uses a one-dimensional array to store a list of customer names.


 Compares the names in the array using equalsIgnoreCase() to check for duplicates (case-
insensitive comparison).
 Prints the duplicate names found in the list.
 Traverses the array using loops to compare all possible pairs of customer names.

14
Object Oriented Programming ______ Lab Session 05
Iqra University Department of Software Engineering

Discussion and analysis of results:

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.

Required Equipment / tools:

 Eclipse
 JDK (Java Development Kit)

Introduction:

Inheritance is a fundamental feature of object-oriented programming that allows one class


(subclass) to inherit the properties and behaviors (fields and methods) of another class
(superclass). It enables the creation of hierarchical structures in which general attributes and
methods are defined in a superclass and inherited by more specific subclasses. Key concepts
include:

 Superclass: The class that is inherited from.


 Subclass: The class that inherits the properties and methods of the superclass.
 Multilevel Inheritance: A subclass can act as a superclass for another class, resulting in
multiple levels of inheritance.
 Method Overriding: A subclass can provide its specific implementation of a method
already defined in the superclass.

Procedure:

1. Inheritance Basics

This task demonstrates basic inheritance by creating a Box class and extending it with a
BoxWeight class.

// This program uses inheritance to extend Box.


class Box {
double width;
double height;
double depth;

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;
}

// constructor used when all dimensions are specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// default constructor when no dimensions are specified


Box() {
width = -1;
height = -1;
depth = -1;
}

// constructor used when a cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

// Here, Box is extended to include weight.


class BoxWeight extends Box {
double weight; // weight of box

// constructor for BoxWeight


BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}

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

Volume of mybox2 is 24.0


Weight of mybox2 is 0.076

2. Multilevel Inheritance

This task demonstrates multilevel inheritance by extending BoxWeight with a Shipment class
that adds a cost attribute.

// Add shipping costs.


class Shipment extends BoxWeight {
double cost;

// construct clone of an object


Shipment(Shipment ob) {
super(ob);
cost = ob.cost;
}

// constructor when all parameters are specified


Shipment(double w, double h, double d, double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}

// default constructor
Shipment() {
13
Object Oriented Programming ______ Lab Session 06
Iqra University Department of Computer Science
super();
cost = -1;
}

// constructor used when a cube is created


Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}

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

Volume of shipment2 is 24.0


Weight of shipment2 is 0.76
Shipping cost: $1.28

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;

Person(String name, String address, String phoneNumber, String email) {


this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
}

public String toString() {


return "Person: " + name;
}
}

class Student extends Person {


final String status;

Student(String name, String address, String phoneNumber, String email, String status) {
super(name, address, phoneNumber, email);
this.status = status;
}

public String toString() {


return "Student: " + name;
}
}

class Employee extends Person {


String office;
double salary;
String dateHired;

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;
}
}

class Faculty extends Employee {


String officeHours, rank;

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;
}

public String toString() {


return "Faculty: " + name;
}
}

class Staff extends Employee {


String title;

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;
}

public String toString() {


return "Staff: " + name;
}
}

public class TestClass {


public static void main(String[] args) {
Person person = new Person("John", "123 Main St", "555-1234", "john@example.com");
Student student = new Student("Alice", "456 Maple St", "555-5678",
"alice@example.com", "Senior");
Employee employee = new Employee("Bob", "789 Oak St", "555-9876",
"bob@example.com", "Office A", 60000, "01-01-2020");
Faculty faculty = new Faculty("Dr. Smith", "321 Birch St", "555-1357",
"smith@example.com", "Office B", 80000, "05-01-2018", "9am-11am", "Professor");
Staff staff = new Staff("Mary", "654 Pine St", "555-2468", "mary@example.com", "Office
C", 50000, "12-12-2021", "HR Manager");

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.

1. Base Class - Vehicle:


o Create a base class named Vehicle, which includes the following attributes:
 A private attribute manufacturer (String): indicating the manufacturer of
the vehicle.
 A private attribute model (String): representing the model of the vehicle.
 A protected attribute manufacturingYear (int): indicating the year in which
the vehicle was manufactured.
o The Vehicle class should consist of:
 A constructor that initializes the manufacturer, model, and
manufacturingYear.
 A method named displayDetails() that returns a formatted string
showcasing the manufacturer, model, and manufacturing year of the
vehicle.

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

Discussion and analysis of results:

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:

 Abstract Methods: Methods that must be implemented by subclasses.


 Abstract Classes: Classes that contain abstract methods and cannot be instantiated.
 Final Methods: Methods that cannot be overridden by subclasses.
 Final Classes: Classes that cannot be inherited from.

Procedure:

1. Abstract Class and Methods

1. Define an Abstract Class:


o Create an abstract class Account with attributes for account ID and balance, and
abstract methods for withdrawal and deposit.

abstract class Account {


protected String id;
protected double balance;

public Account(String id, double balance) {


this.id = id;
this.balance = balance;
}

public String getID() {


return id;
}

public double getBalance() {


return balance;
}

public abstract boolean withdraw(double amount);


public abstract void deposit(double amount);
}

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
}
}

3. Test the Implementation:


o Create a main method to test the SavingsAccount functionality.

public class BankApplication {


public static void main(String[] args) {
SavingsAccount account = new SavingsAccount("12345", 50.0);
account.deposit(20);
System.out.println("Balance after deposit: " + account.getBalance());
boolean result = account.withdraw(30);
System.out.println("Withdrawal successful: " + result);
System.out.println("Balance after withdrawal: " + account.getBalance());
}
}
1. Final Methods and Classes

1. Define a Final Class:


o Create a class marked as final to prevent inheritance.

final class FinalClass {


public final void displayMessage() {
System.out.println("This is a final method in a final class.");
}
}

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.

class AttemptInheritance extends FinalClass { // This will cause a compile-time error


public void newMethod() {
System.out.println("Trying to inherit.");
}
}

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:

1. Create an Abstract Class:


o Define an abstract class named Account with the following attributes:
 protected String id
 protected double balance
o Implement the following methods:

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.

3. Test the Implementation:


o In the main method, create an instance of SavingsAccount, perform some deposits
and withdrawals, and print the resulting balances to verify the functionality.

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:

1. Create a Final Class:


o Define a class named ShippingBox as a final class that includes:
 double width, double height, double depth: Attributes for the dimensions
of the box.
 A constructor that initializes these dimensions.
 A method double calculateVolume(): Calculates and returns the volume of
the box.

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:

1. Create a Base Class:


o Define a class named Person with fields for name, address, phone number, and
email. Implement a constructor to initialize these fields.

2. Use Abstract Classes:


o Extend Person to create an abstract class named Employee that includes:
 Fields for salary and date hired.
 An abstract method public abstract String getDetails(): To retrieve
employee details.

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.

4. Test the Implementation:


o In the main method, create instances of Faculty and Staff, print their details using
the getDetails() method to demonstrate the use of inheritance and polymorphism.

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

Discussion and analysis of results:

Conclusion:

23

You might also like