0% found this document useful (0 votes)
10 views35 pages

Oop Lab Ass # 3

The document discusses object oriented programming concepts like classes, inheritance, polymorphism and abstraction. It defines classes like Movie, Action, Comedy etc and demonstrates polymorphism by calculating late fees using the calcLateFees method. It also defines classes like Simple, VerifiedSimple and demonstrates inheritance.

Uploaded by

Muhammad Nouman
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)
10 views35 pages

Oop Lab Ass # 3

The document discusses object oriented programming concepts like classes, inheritance, polymorphism and abstraction. It defines classes like Movie, Action, Comedy etc and demonstrates polymorphism by calculating late fees using the calcLateFees method. It also defines classes like Simple, VerifiedSimple and demonstrates inheritance.

Uploaded by

Muhammad Nouman
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/ 35

OOP

Lab Assignment # 3

DECEMBER 13, 2023


MUHAMMAD NOUMAN
FA22-BDS-028
Lab 7
Task1
class Movie {

private String rating;

private int id;

private String title;

public Movie(String rating, int id, String title) {

this.rating = rating;

this.id = id;

this.title = title;

public String getRating() {

return rating;

public void setRating(String rating) {

this.rating = rating;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

}
public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public double calcLateFees(int daysLate) {

return 2.0 * daysLate; // Default late fee

@Override

public boolean equals(Object obj) {

// if (this == obj) {

// return true;

// }

// if (obj == null || getClass() != obj.getClass()) {

// return false;

// }

Movie otherMovie = (Movie) obj;

return id == otherMovie.id;

class Action extends Movie {

public Action(String rating, int id, String title) {

super(rating, id, title);


}

@Override

public double calcLateFees(int daysLate) {

return 3.0 * daysLate; // Action movie late fee

class Comedy extends Movie {

public Comedy(String rating, int id, String title) {

super(rating, id, title);

@Override

public double calcLateFees(int daysLate) {

return 2.5 * daysLate; // Comedy movie late fee

class Drama extends Movie {

public Drama(String rating, int id, String title) {

super(rating, id, title);

public class Task1 {

public static void main(String[] args) {

Movie movie1 = new Movie("PG", 1, "The Matrix");

Movie movie2 = new Action("R", 2, "Die Hard");


Movie movie3 = new Comedy("PG-13", 3, "Dumb and Dumber");

Movie movie4 = new Drama("PG", 4, "Forrest Gump");

// Test equals() method

System.out.println("Are movie1 and movie2 equal? " + movie1.equals(movie2));

System.out.println("Are movie1 and movie1 equal? " + movie1.equals(movie1));

// Test calcLateFees method using polymorphism

System.out.println("Late fee for movie1: $" + movie1.calcLateFees(5));

System.out.println("Late fee for movie2: $" + movie2.calcLateFees(3));

System.out.println("Late fee for movie3: $" + movie3.calcLateFees(2));

System.out.println("Late fee for movie4: $" + movie4.calcLateFees(4));

Task 2
class Simple {

int num1;

int num2;

public Simple(int num1, int num2) {

this.num1 = num1;

this.num2 = num2;

}
public void add() {

double sum=num1+num2;

System.out.println("Sum :"+sum) ;

public void sub() {

System.out.println("Difference: " + (num1 - num2));

public void mul() {

System.out.println("Product: " + (num1 * num2));

public void div() {

if (num2 != 0) {

System.out.println("Quotient: " + ((double) num1 / num2));

} else {

System.out.println("Error: Cannot divide by zero.");

class VerifiedSimple extends Simple {

public VerifiedSimple(int num1, int num2) {

super(num1, num2);

@Override
public void add() {

if (num1 > 0 && num2 > 0) {

super.add();

} else {

System.out.println("Error: Numbers must be greater than 0 for addition.");

@Override

public void sub() {

if (num1 > 0 && num2 > 0) {

super.sub();

} else {

System.out.println("Error: Numbers must be greater than 0 for subtraction.");

@Override

public void mul() {

if (num1 > 0 && num2 > 0) {

super.mul();

} else {

System.out.println("Error: Numbers must be greater than 0 for multiplication.");

@Override

public void div() {

if (num1 > 0 && num2 > 0) {


super.div();

} else {

System.out.println("Error: Numbers must be greater than 0 for division.");

public class Task2 {

public static void main(String[] args) {

Simple simpleObj = new Simple(5, 3);

System.out.println("Simple Class:");

simpleObj.add();

simpleObj.sub();

simpleObj.mul();

simpleObj.div();

System.out.println();

VerifiedSimple verifiedSimpleObj = new VerifiedSimple(1, 8);

System.out.println("VerifiedSimple Class:");

verifiedSimpleObj.add();

verifiedSimpleObj.sub();

verifiedSimpleObj.mul();

verifiedSimpleObj.div();

}
Task 3
abstract class Shape {

protected int numberOfLines;

protected String penColor;

protected String fillColor;

public Shape(int numberOfLines, String penColor, String fillColor) {

this.numberOfLines = numberOfLines;

this.penColor = penColor;

this.fillColor = fillColor;

public abstract void draw();

class Circle extends Shape {

private double radius;

public Circle(double radius, String penColor, String fillColor) {

super(1, penColor, fillColor);

this.radius = radius;
}

@Override

public void draw() {

System.out.println("Drawing Circle with Radius: " + radius);

System.out.println("Pen Color: " + penColor);

System.out.println("Fill Color: " + fillColor);

// Additional logic for drawing a circle on screen can be added here

class Square extends Shape {

private double side;

public Square(double side, String penColor, String fillColor) {

super(4, penColor, fillColor);

this.side = side;

@Override

public void draw() {

System.out.println("Drawing Square with Side: " + side);

System.out.println("Pen Color: " + penColor);

System.out.println("Fill Color: " + fillColor);

// Additional logic for drawing a square on screen can be added here

class Triangle extends Shape {


private double base;

private double height;

public Triangle(double base, double height, String penColor, String fillColor) {

super(3, penColor, fillColor);

this.base = base;

this.height = height;

@Override

public void draw() {

System.out.println("Drawing Triangle with Base: " + base + " and Height: " + height);

System.out.println("Pen Color: " + penColor);

System.out.println("Fill Color: " + fillColor);

// Additional logic for drawing a triangle on screen can be added here

public class Task3 {

public static void main(String[] args) {

Circle circle = new Circle(5.0, "Blue", "Yellow");

Square square = new Square(4.0, "Red", "Green");

Triangle triangle = new Triangle(3.0, 4.0, "Black", "Orange");

System.out.println("Drawing Shapes:");

circle.draw();

square.draw();

triangle.draw();

}
}

Lab 8
Task1
class Package {

private String senderName;

private String senderAddress;

private String recipientName;

private String recipientAddress;

private double weight;

private double costPerOunce;

public Package(String senderName, String senderAddress, String recipientName, String


recipientAddress,

double weight, double costPerOunce) {

this.senderName = senderName;

this.senderAddress = senderAddress;

this.recipientName = recipientName;

this.recipientAddress = recipientAddress;

if (weight > 0) {

this.weight = weight;
} else {

throw new IllegalArgumentException("Weight must be positive.");

if (costPerOunce > 0) {

this.costPerOunce = costPerOunce;

} else {

throw new IllegalArgumentException("Cost per ounce must be positive.");

public double calculateCost() {

return weight * costPerOunce;

class TwoDayPackage extends Package {

private double flatFee;

public TwoDayPackage(String senderName, String senderAddress, String recipientName, String


recipientAddress,

double weight, double costPerOunce, double flatFee) {

super(senderName, senderAddress, recipientName, recipientAddress, weight, costPerOunce);

if (flatFee >= 0) {

this.flatFee = flatFee;

} else {

throw new IllegalArgumentException("Flat fee must be non-negative.");

}
@Override

public double calculateCost() {

return super.calculateCost() + flatFee;

class OvernightPackage extends Package {

private double additionalFee;

public OvernightPackage(String senderName, String senderAddress, String recipientName, String


recipientAddress,

double weight, double costPerOunce, double additionalFee) {

super(senderName, senderAddress, recipientName, recipientAddress, weight, costPerOunce);

if (additionalFee >= 0) {

this.additionalFee = additionalFee;

} else {

throw new IllegalArgumentException("Additional fee must be non-negative.");

@Override

public double calculateCost() {

return super.calculateCost() + additionalFee;

public class Task1 {

public static void main(String[] args) {


Package package1 = new Package("John Doe", "123 Main St", "Jane Doe", "456 Broad St", 10, 2.5);

TwoDayPackage package2 = new TwoDayPackage("Alice Smith", "789 Oak St", "Bob Johnson", "321
Pine St", 8, 3.0, 5.0);

OvernightPackage package3 = new OvernightPackage("Eva Williams", "567 Birch St", "Charlie


Brown", "654 Elm St", 5, 4.0, 8.0);

System.out.println("Cost for Package 1: $" + package1.calculateCost());

System.out.println("Cost for TwoDayPackage 2: $" + package2.calculateCost());

System.out.println("Cost for OvernightPackage 3: $" + package3.calculateCost());

Task2

abstract class Person {

private String name;

public Person(String name) {

this.name = name;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

}
public abstract boolean isOutstanding();

class Student extends Person {

private double CGPA;

public Student(String name, double CGPA) {

super(name);

this.CGPA = CGPA;

public double getCGPA() {

return CGPA;

public void setCGPA(double CGPA) {

this.CGPA = CGPA;

@Override

public boolean isOutstanding() {

return CGPA > 3.5;

class Professor extends Person {

private int numberOfPublications;


public Professor(String name, int numberOfPublications) {

super(name);

this.numberOfPublications = numberOfPublications;

public int getNumberOfPublications() {

return numberOfPublications;

public void setNumberOfPublications(int numberOfPublications) {

this.numberOfPublications = numberOfPublications;

@Override

public boolean isOutstanding() {

return numberOfPublications > 50;

public class Task2 {

public static void main(String[] args) {

Person[] people = new Person[2];

people[0] = new Student("Alice", 3.8);

people[1] = new Professor("Dr. Smith", 30);

for (Person person : people) {

System.out.println("Name: " + person.getName());

System.out.println("Is Outstanding: " + person.isOutstanding());

System.out.println("---------------");
}

// Updating the professor's publication count

Professor professor = (Professor) people[1];

professor.setNumberOfPublications(100);

// Calling isOutstanding() for the professor after updating the publication count

System.out.println("Is Outstanding (After updating publication count): " +


professor.isOutstanding());

Task 3

abstract class Convert {

protected double val1; // initial value

protected double val2; // converted value

public Convert(double val1) {

this.val1 = val1;

public abstract void compute(); // abstract method for performing the conversion
public void displayResult() {

System.out.println("Initial Value: " + val1);

System.out.println("Converted Value: " + val2);

class LitersToGallons extends Convert {

public LitersToGallons(double liters) {

super(liters);

@Override

public void compute() {

val2 = val1 * 0.264172; // 1 liter is approximately 0.264172 gallons

class FahrenheitToCelsius extends Convert {

public FahrenheitToCelsius(double fahrenheit) {

super(fahrenheit);

@Override

public void compute() {

val2 = (val1 - 32) * 5 / 9; // Conversion formula from Fahrenheit to Celsius

class FeetToMeters extends Convert {


public FeetToMeters(double feet) {

super(feet);

@Override

public void compute() {

val2 = val1 * 0.3048; // 1 foot is approximately 0.3048 meters

public class Task3 {

public static void main(String[] args) {

// Test Liters to Gallons conversion

Convert l_to_g = new LitersToGallons(10);

l_to_g.compute();

System.out.println("Liters to Gallons Conversion:");

l_to_g.displayResult();

System.out.println();

// Test Fahrenheit to Celsius conversion

Convert f_to_c = new FahrenheitToCelsius(212);

f_to_c.compute();

System.out.println("Fahrenheit to Celsius Conversion:");

f_to_c.displayResult();

System.out.println();

// Test Feet to Meters conversion

Convert f_to_m = new FeetToMeters(30);

f_to_m.compute();
System.out.println("Feet to Meters Conversion:");

f_to_m.displayResult();

Lab 10
Task1

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Scanner;

class Contact {

private String firstName;

private String lastName;

private String phoneNumber;

private String emailAddress;

// Constructor

public Contact(String firstName, String lastName, String phoneNumber, String emailAddress) {

this.firstName = firstName;
this.lastName = lastName;

this.phoneNumber = phoneNumber;

this.emailAddress = emailAddress;

// Accessor and mutator methods for each field

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getPhoneNumber() {

return phoneNumber;

public void setPhoneNumber(String phoneNumber) {

this.phoneNumber = phoneNumber;

}
public String getEmailAddress() {

return emailAddress;

public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;

public class Task1 {

private static ArrayList<Contact> contacts = new ArrayList<>();

private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {

int choice;

do {

System.out.println("1. Add a contact");

System.out.println("2. Display all contacts");

System.out.println("3. Search for a contact");

System.out.println("4. Delete a contact");

System.out.println("5. Exit");

System.out.print("Enter your choice: ");

choice = scanner.nextInt();

switch (choice) {

case 1:

addContact();
break;

case 2:

displayAllContacts();

break;

case 3:

searchAndDisplayContact();

break;

case 4:

deleteContact();

break;

case 5:

System.out.println("Exiting the program. Goodbye!");

break;

default:

System.out.println("Invalid choice. Please enter a valid option.");

} while (choice != 5);

private static void addContact() {

System.out.print("Enter first name: ");

String firstName = scanner.next();

System.out.print("Enter last name: ");

String lastName = scanner.next();

System.out.print("Enter phone number: ");

String phoneNumber = scanner.next();


System.out.print("Enter email address: ");

String emailAddress = scanner.next();

Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);

contacts.add(newContact);

System.out.println("Contact added successfully.");

private static void displayAllContacts() {

if (contacts.isEmpty()) {

System.out.println("No contacts available.");

} else {

System.out.println("All contacts:");

for (Contact contact : contacts) {

displayContact(contact);

private static void searchAndDisplayContact() {

System.out.print("Enter search string: ");

String searchString = scanner.next().toLowerCase();

ArrayList<Contact> searchResults = new ArrayList<>();

for (Contact contact : contacts) {

if (contact.getFirstName().toLowerCase().contains(searchString) ||

contact.getLastName().toLowerCase().contains(searchString) ||
contact.getPhoneNumber().toLowerCase().contains(searchString) ||

contact.getEmailAddress().toLowerCase().contains(searchString)) {

searchResults.add(contact);

if (searchResults.isEmpty()) {

System.out.println("No matching contacts found.");

} else {

System.out.println("Matching contacts:");

for (Contact contact : searchResults) {

displayContact(contact);

private static void deleteContact() {

System.out.print("Enter search string to find the contact to delete: ");

String searchString = scanner.next().toLowerCase();

Iterator<Contact> iterator = contacts.iterator();

while (iterator.hasNext()) {

Contact contact = iterator.next();

if (contact.getFirstName().toLowerCase().contains(searchString) ||

contact.getLastName().toLowerCase().contains(searchString) ||

contact.getPhoneNumber().toLowerCase().contains(searchString) ||

contact.getEmailAddress().toLowerCase().contains(searchString)) {

iterator.remove();
System.out.println("Contact deleted successfully.");

return;

System.out.println("No matching contact found for deletion.");

private static void displayContact(Contact contact) {

System.out.println("First Name: " + contact.getFirstName());

System.out.println("Last Name: " + contact.getLastName());

System.out.println("Phone Number: " + contact.getPhoneNumber());

System.out.println("Email Address: " + contact.getEmailAddress());

System.out.println("--------------------");

}
}

Task 2

import java.util.ArrayList;

public class Task2<T extends Number> {

public double standardDeviation(ArrayList<T> numbers) {

if (numbers == null || numbers.size() < 2) {

throw new IllegalArgumentException("At least two values are required to calculate standard
deviation.");
}

double mean = calculateMean(numbers);

double sumSquaredDifferences = 0.0;

for (T num : numbers) {

double difference = num.doubleValue() - mean;

sumSquaredDifferences += difference * difference;

double variance = sumSquaredDifferences / (numbers.size() - 1);

return Math.sqrt(variance);

private double calculateMean(ArrayList<T> numbers) {

double sum = 0.0;

for (T num : numbers) {

sum += num.doubleValue();

return sum / numbers.size();

public static void main(String[] args) {

// Testing the standardDeviation method

ArrayList<Integer> intList = new ArrayList<>();

intList.add(2);

intList.add(4);

intList.add(4);

intList.add(4);
intList.add(5);

intList.add(5);

intList.add(7);

intList.add(9);

Task2<Integer> myMath = new Task2<>(); // Corrected class name

double result = myMath.standardDeviation(intList);

System.out.println("Standard Deviation: " + result);

Task 3

import java.util.ArrayList;

import java.util.Random;

public class Task3<T> {

private ArrayList<T> box;

private Random random;

public Task3() {

box = new ArrayList<>();

random = new Random();

public void add(T item) {


box.add(item);

public boolean isEmpty() {

return box.isEmpty();

public T drawItem() {

if (isEmpty()) {

return null;

int randomIndex = random.nextInt(box.size());

return box.remove(randomIndex);

public static void main(String[] args) {

Task3<String> nameBox = new Task3<>();

// Adding names to the box

nameBox.add("Alice");

nameBox.add("Bob");

nameBox.add("Charlie");

nameBox.add("David");

// Drawing names from the box

System.out.println("Drawing names from the box:");

while (!nameBox.isEmpty()) {

String drawnName = nameBox.drawItem();


System.out.println("Drawn: " + drawnName);

// Testing with Integer

Task3<Integer> numberBox = new Task3<>();

// Adding numbers to the box

for (int i = 1; i <= 10; i++) {

numberBox.add(i);

// Drawing numbers from the box

System.out.println("\nDrawing numbers from the box:");

while (!numberBox.isEmpty()) {

Integer drawnNumber = numberBox.drawItem();

System.out.println("Drawn: " + drawnNumber);

}
Task 4

import java.util.ArrayList;

import java.util.Collections;

import java.util.Scanner;

public class Task4 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input degree of difficulty

System.out.print("Enter the degree of difficulty (1.2 to 3.8): ");

double difficulty = scanner.nextDouble();

// Input scores from seven judges

ArrayList<Double> scores = new ArrayList<>();


for (int i = 1; i <= 7; i++) {

System.out.print("Enter judge " + i + "'s score (0 to 10): ");

double score = scanner.nextDouble();

// Validate that the score is within the valid range

if (score < 0 || score > 10) {

System.out.println("Invalid score. Scores must be between 0 and 10.");

System.exit(1);

scores.add(score);

// Calculate overall score

double overallScore = calculateOverallScore(difficulty, scores);

// Output the result

System.out.println("Overall score: " + overallScore);

scanner.close();

private static double calculateOverallScore(double difficulty, ArrayList<Double> scores) {

// Sort the scores and remove the highest and lowest

Collections.sort(scores);

scores.remove(0); // remove lowest

scores.remove(scores.size() - 1); // remove highest

// Sum the remaining scores


double sum = 0;

for (double score : scores) {

sum += score;

// Multiply by degree of difficulty

double result = sum * difficulty;

// Multiply by 0.6

return result * 0.6;

You might also like