You are on page 1of 31

KWAME NKRUMAH UNIVERSITY

IN ASSOCIATION WITH

KABWE INSTITUTE OF TECHNOLOGY

NAME:

PROGRAM:

COURSE:

DUE DATE:

LECTURER:
TASK 1 : Classes and Objects

public class Rectangle {

private double width;

private double height;

// Constructor to initialize the attributes

public Rectangle(double width, double height) {

this.width = width;

this.height = height;

// Calculate the area of the rectangle

public double calculateArea() {

return width * height;

// Calculate the perimeter of the rectangle

public double calculatePerimeter() {

return 2 * (width + height);

public static void main(String[] args) {

// Create a rectangle object with width 5 and height 10

Rectangle myRectangle = new Rectangle(5, 10);


// Calculate and print the area and perimeter

System.out.println("Rectangle Area: " + myRectangle.calculateArea());

System.out.println("Rectangle Perimeter: " + myRectangle.calculatePerimeter());

In this class:

We have private attributes width and height to represent the dimensions of the rectangle.

The constructor Rectangle(double width, double height) initializes these attributes when a Rectangle
object is created.

The calculateArea() function calculates the area of the rectangle by multiplying width and height.

The calculatePerimeter() function calculates the perimeter of the rectangle using the formula 2 * (width
+ height).

In the main() method, we create a Rectangle object with a width of 5 and a height of 10, and then
calculate and print the area and perimeter.

TASK 2: Operator Overloading

public class Rectangle {

private double width;

private double height;

// Constructor to initialize the attributes

public Rectangle(double width, double height) {

this.width = width;

this.height = height;

}
// Calculate the area of the rectangle

public double calculateArea() {

return width * height;

// Calculate the perimeter of the rectangle

public double calculatePerimeter() {

return 2 * (width + height);

// Overload the + operator to add two rectangles

public Rectangle add(Rectangle otherRectangle) {

double newWidth = this.width + otherRectangle.width;

double newHeight = this.height + otherRectangle.height;

return new Rectangle(newWidth, newHeight);

public static void main(String[] args) {

// Create two rectangles

Rectangle rectangle1 = new Rectangle(5, 10);

Rectangle rectangle2 = new Rectangle(3, 7);

// Add the two rectangles to get a new rectangle

Rectangle sumRectangle = rectangle1.add(rectangle2);

// Calculate and print the area and perimeter of the sumRectangle


System.out.println("Sum Rectangle Area: " + sumRectangle.calculateArea());

System.out.println("Sum Rectangle Perimeter: " + sumRectangle.calculatePerimeter());

In this updated class:

We have added a new method add(Rectangle otherRectangle) that overloads the + operator. This
method takes another Rectangle as a parameter, calculates the sum of their dimensions, and returns a
new Rectangle with those dimensions.

In the main() method, we create two Rectangle objects, rectangle1 and rectangle2, and then use the
add() method to add them together to get a new sumRectangle. Finally, we calculate and print the area
and perimeter of the sumRectangle.

TASK 3: : Inheritance

A)

class Shape {

// Member function to calculate the area (default implementation)

public double area() {

return 0;

public class TypecastingDemo {

public static void main(String[] args) {

// Demonstrating casting from int to double

int intValue = 42;

double doubleValue = (double) intValue;

System.out.println("int to double:");
System.out.println("Original int value: " + intValue);

System.out.println("Cast to double: " + doubleValue);

// Demonstrating casting from double to int

double doubleValue2 = 3.14;

int intValue2 = (int) doubleValue2;

System.out.println("\ndouble to int:");

System.out.println("Original double value: " + doubleValue2);

System.out.println("Cast to int: " + intValue2);

This program first demonstrates casting from int to double by explicitly casting the intValue to a double.
Then, it demonstrates casting from double to int by explicitly casting the doubleValue2 to an int. When
you run this program, you'll see how the values change after typecasting.

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 0); // Example usage with division by zero

System.out.println("Result of division: " + result);

} catch (ArithmeticException e) {

System.err.println("Error: Division by zero is not allowed.");


}

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

return numerator / denominator;

In this program, the divideNumber() function takes two integers as input, checks if the denominator is
zero, and if it is, it throws an ArithmeticException with an error message. In the main() method, we call
this function with an example where the denominator is zero and catch the exception to handle the
division by zero error.

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 2); // Valid division

System.out.println("Result of division: " + result);

result = divideNumber(10, 0); // Division by zero

System.out.println("Result of division: " + result); // This line won't be executed

} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

return numerator / denominator;

In this program, We first call divideNumber(10, 2) with a valid division, which will print the result.

Then, we call divideNumber(10, 0) with division by zero, which will throw an ArithmeticException. We
catch this exception and print the error message.

This program demonstrates the use of the divideNumber() function and how it handles exceptions when
division by zero occurs.

B)

public class TypecastingDemo {

public static void main(String[] args) {

// Demonstrating casting from int to double

int intValue = 42;

double doubleValue = (double) intValue;


System.out.println("int to double:");

System.out.println("Original int value: " + intValue);

System.out.println("Cast to double: " + doubleValue);

// Demonstrating casting from double to int

double doubleValue2 = 3.14;

int intValue2 = (int) doubleValue2;

System.out.println("\ndouble to int:");

System.out.println("Original double value: " + doubleValue2);

System.out.println("Cast to int: " + intValue2);

This program first demonstrates casting from int to double by explicitly casting the intValue to a double.
Then, it demonstrates casting from double to int by explicitly casting the doubleValue2 to an int. When
you run this program, you'll see how the values change after typecasting.

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 0); // Example usage with division by zero

System.out.println("Result of division: " + result);

} catch (ArithmeticException e) {
System.err.println("Error: Division by zero is not allowed.");

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

return numerator / denominator;

In this program, the divideNumber() function takes two integers as input, checks if the denominator is
zero, and if it is, it throws an ArithmeticException with an error message. In the main() method, we call
this function with an example where the denominator is zero and catch the exception to handle the
division by zero error.

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 2); // Valid division

System.out.println("Result of division: " + result);

result = divideNumber(10, 0); // Division by zero

System.out.println("Result of division: " + result); // This line won't be executed


} catch (ArithmeticException e) {

System.err.println("Error: " + e.getMessage());

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

return numerator / denominator;

In this program, We first call divideNumber(10, 2) with a valid division, which will print the result.

Then, we call divideNumber(10, 0) with division by zero, which will throw an ArithmeticException. We
catch this exception and print the error message.

This program demonstrates the use of the divideNumber() function and how it handles exceptions when
division by zero occurs.

"OOP_Templates_Assignment.zip"}

// Derived class Circle

class Circle extends Shape {

private double radius;

// Constructor to initialize the radius

public Circle(double radius) {

this.radius = radius;
}

// Override the area() function to calculate the area of a circle

@Override

public double area() {

return Math.PI * radius * radius;

// Derived class Triangle

class Triangle extends Shape {

private double base;

private double height;

// Constructor to initialize the base and height

public Triangle(double base, double height) {

this.base = base;

this.height = height;

// Override the area() function to calculate the area of a triangle

@Override

public double area() {

return 0.5 * base * height;

}
}

public class ShapeDemo {

public static void main(String[] args) {

// Create a Circle object and calculate its area

Circle circle = new Circle(5.0);

System.out.println("Circle Area: " + circle.area());

// Create a Triangle object and calculate its area

Triangle triangle = new Triangle(4.0, 7.0);

System.out.println("Triangle Area: " + triangle.area());

In this program:

We define a base class Shape with a default implementation of the area() function that returns 0.

We derive two classes, Circle and Triangle, from the base class.

In the Circle class, we override the area() function to calculate the area of a circle using the formula πr².

In the Triangle class, we override the area() function to calculate the area of a triangle using the formula
0.5 * base * height.

In the main() method, we create instances of Circle and Triangle, calculate and print their respective
areas.

TASK 4: Polymorphism and Virtual Functions

A)

// Base class Shape


class Shape {

// Member function to calculate the area (default implementation)

public double area() {

return 0;

// Derived class Circle

class Circle extends Shape {

private double radius;

// Constructor to initialize the radius

public Circle(double radius) {

this.radius = radius;

// Override the area() function to calculate the area of a circle

@Override

public double area() {

return Math.PI * radius * radius;

// Derived class Triangle

class Triangle extends Shape {


private double base;

private double height;

// Constructor to initialize the base and height

public Triangle(double base, double height) {

this.base = base;

this.height = height;

// Override the area() function to calculate the area of a triangle

@Override

public double area() {

return 0.5 * base * height;

// Derived class Square

class Square extends Shape {

private double side;

// Constructor to initialize the side

public Square(double side) {

this.side = side;

}
// Override the area() function to calculate the area of a square

@Override

public double area() {

return side * side;

public class ShapeDemo {

public static void main(String[] args) {

// Create a Circle object and calculate its area

Circle circle = new Circle(5.0);

System.out.println("Circle Area: " + circle.area());

// Create a Triangle object and calculate its area

Triangle triangle = new Triangle(4.0, 7.0);

System.out.println("Triangle Area: " + triangle.area());

// Create a Square object and calculate its area

Square square = new Square(6.0);

System.out.println("Square Area: " + square.area());

In this expanded program:We add a new class Square derived from the base class Shape.

In the Square class, we override the area() function to calculate the area of a square using the formula
side * side.
In the main() method, we create instances of Circle, Triangle, and Square, calculate and print their
respective areas.

B)

class Shape {

public double area() {

return 0;

class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double area() {

return Math.PI * radius * radius;

class Triangle extends Shape {

private double base;


private double height;

public Triangle(double base, double height) {

this.base = base;

this.height = height;

@Override

public double area() {

return 0.5 * base * height;

class Square extends Shape {

private double side;

public Square(double side) {

this.side = side;

@Override

public double area() {

return side * side;

}
public class ShapeDemo {

public static double calculateTotalArea(Shape[] shapes) {

double totalArea = 0;

for (Shape shape : shapes) {

totalArea += shape.area();

return totalArea;

public static void main(String[] args) {

Circle circle = new Circle(5.0);

Triangle triangle = new Triangle(4.0, 7.0);

Square square = new Square(6.0);

Shape[] shapes = { circle, triangle, square };

double totalArea = calculateTotalArea(shapes);

System.out.println("Total Area of Shapes: " + totalArea);

In this program:

We define a calculateTotalArea() function that takes an array of Shape objects.


Inside this function, we iterate through the array of shapes and use polymorphism to call the area()
method for each shape, which calculates its area based on the overridden method in the respective
derived class.

We accumulate the areas of all the shapes to calculate the total area.

In the main() method, we create instances of Circle, Triangle, and Square, put them in an array of Shape,
and then call calculateTotalArea() to compute and print the total area of all shapes using polymorphism.

Task 5: Encapsulation

public class Student {

private String name;

private int age;

private int rollNumber;

// Constructor to initialize the Student object

public Student(String name, int age, int rollNumber) {

this.name = name;

this.age = age;

this.rollNumber = rollNumber;

// Getter method for name

public String getName() {

return name;

// Setter method for name


public void setName(String name) {

this.name = name;

// Getter method for age

public int getAge() {

return age;

// Setter method for age

public void setAge(int age) {

this.age = age;

// Getter method for rollNumber

public int getRollNumber() {

return rollNumber;

// Setter method for rollNumber

public void setRollNumber(int rollNumber) {

this.rollNumber = rollNumber;

public static void main(String[] args) {


// Create a Student object

Student student = new Student("John", 20, 101);

// Get and print student details

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

System.out.println("Age: " + student.getAge());

System.out.println("Roll Number: " + student.getRollNumber());

// Update student details

student.setName("Alice");

student.setAge(22);

student.setRollNumber(102);

// Get and print updated student details

System.out.println("\nUpdated Details:");

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

System.out.println("Age: " + student.getAge());

System.out.println("Roll Number: " + student.getRollNumber());

In this class:

We have private attributes name, age, and rollNumber to represent the student's information.

We provide public getter methods (getName(), getAge(), getRollNumber()) to access the attribute
values.

We provide public setter methods (setName(), setAge(), setRollNumber()) to update the attribute
values.
In the main() method, we create a Student object, get and print its initial details, update the details
using setter methods, and then get and print the updated details.

UNIT 3

TASK 1: : Function Templates and Class Templates

A)

public class MaximumFinder<T extends Comparable<T>> {

public T findMaximum(T value1, T value2) {

if (value1.compareTo(value2) > 0) {

return value1;

} else {

return value2;

public static void main(String[] args) {

MaximumFinder<Integer> integerMaximumFinder = new MaximumFinder<>();

MaximumFinder<Double> doubleMaximumFinder = new MaximumFinder<>();

MaximumFinder<String> stringMaximumFinder = new MaximumFinder<>();

int maxInt = integerMaximumFinder.findMaximum(5, 10);

double maxDouble = doubleMaximumFinder.findMaximum(3.5, 7.2);

String maxString = stringMaximumFinder.findMaximum("apple", "banana");

System.out.println("Maximum Integer: " + maxInt);


System.out.println("Maximum Double: " + maxDouble);

System.out.println("Maximum String: " + maxString);

In this example, we've created a generic class MaximumFinder that uses a type parameter T which must
extend the Comparable interface. The findMaximum method compares the two values using compareTo
and returns the maximum value.

You can create instances of MaximumFinder with different types and find the maximum value for those
types.

B)

public class Pair<T, U> {

private T firstValue;

private U secondValue;

public Pair(T firstValue, U secondValue) {

this.firstValue = firstValue;

this.secondValue = secondValue;

public T getFirstValue() {

return firstValue;

public void setFirstValue(T firstValue) {


this.firstValue = firstValue;

public U getSecondValue() {

return secondValue;

public void setSecondValue(U secondValue) {

this.secondValue = secondValue;

public static void main(String[] args) {

Pair<Integer, String> pair = new Pair<>(10, "Hello");

System.out.println("First Value: " + pair.getFirstValue());

System.out.println("Second Value: " + pair.getSecondValue());

pair.setFirstValue(20);

pair.setSecondValue("World");

System.out.println("Updated First Value: " + pair.getFirstValue());

System.out.println("Updated Second Value: " + pair.getSecondValue());

In this example, we've created a generic class Pair that takes two type parameters T and U to represent
the types of the first and second values in the pair. The class includes member functions getFirstValue
and getSecondValue to retrieve the values, as well as setFirstValue and setSecondValue to set new
values for the pair. The main method demonstrates how to use this Pair class with different types.

TASK 2: Name Spaces and Casting

A)

#include <iostream>

// Define the Geometry namespace

namespace Geometry {

class Rectangle {

private:

double width;

double height;

public:

// Constructor to initialize the attributes

Rectangle(double w, double h) : width(w), height(h) {}

// Calculate the area of the rectangle

double calculateArea() {

return width * height;

}
// Calculate the perimeter of the rectangle

double calculatePerimeter() {

return 2 * (width + height);

};

int main() {

// Create a Rectangle object inside the Geometry namespace

Geometry::Rectangle myRectangle(5.0, 10.0);

// Calculate and print the area and perimeter

std::cout << "Rectangle Area: " << myRectangle.calculateArea() << std::endl;

std::cout << "Rectangle Perimeter: " << myRectangle.calculatePerimeter() << std::endl;

return 0;

In this C++ program:

We define a namespace named Geometry using namespace Geometry { ... }.

Inside the Geometry namespace, we include the Rectangle class with its attributes, constructor, and
member functions as in the previous task.

In the main() function, we create a Rectangle object inside the Geometry namespace and use it to
calculate and print the area and perimeter.

By placing the Rectangle class inside the Geometry namespace, you can ensure that it is encapsulated
within that namespace and can be accessed using the scope resolution operator :: as shown in the
main() function.
B)

public class TypeCastingDemo {

public static void main(String[] args) {

// Type casting from int to double

int intValue = 42;

double doubleValue = (double) intValue; // Explicit casting

System.out.println("int to double:");

System.out.println("Original int value: " + intValue);

System.out.println("Casted to double: " + doubleValue);

// Type casting from double to int

double doubleValue2 = 3.14;

int intValue2 = (int) doubleValue2; // Explicit casting

System.out.println("\ndouble to int:");

System.out.println("Original double value: " + doubleValue2);

System.out.println("Casted to int: " + intValue2);

// Type casting from double to int (with rounding)

double doubleValue3 = 3.75;

int intValue3 = (int) doubleValue3; // Implicit casting with rounding

System.out.println("\ndouble to int (with rounding):");

System.out.println("Original double value: " + doubleValue3);


System.out.println("Casted to int (with rounding): " + intValue3);

In this program:

We demonstrate type casting from int to double by explicitly casting the intValue to a double.

We demonstrate type casting from double to int by explicitly casting the doubleValue2 to an int.

We also demonstrate type casting from double to int with rounding. When you explicitly cast a double
to an int, it truncates the decimal part, effectively rounding towards zero.

Running this program will show how the values change after type casting.

public class MaximumFinder<T extends Comparable<T>> {

TASK 3: : Exception Handling

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 0); // Example usage with division by zero

System.out.println("Result of division: " + result);

} catch (ArithmeticException e) {

System.err.println("Error: Division by zero is not allowed.");

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");


}

return numerator / denominator;

In this program, the divideNumber() function takes two integers as input, checks if the denominator is
zero, and if it is, it throws an ArithmeticException with an error message. In the main() method, we call
this function with an example where the denominator is zero and catch the exception to handle the
division by zero error.

B)

public class DivisionDemo {

public static void main(String[] args) {

try {

int result = divideNumber(10, 2); // Valid division

System.out.println("Result of division: " + result);

result = divideNumber(10, 0); // Division by zero

System.out.println("Result of division: " + result); // This line won't be executed

} catch (ArithmeticException e) {

System.err.println("Error: " + e.getMessage());

public static int divideNumber(int numerator, int denominator) {

if (denominator == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

}
return numerator / denominator;

In this program, We first call divideNumber(10, 2) with a valid division, which will print the result.

Then, we call divideNumber(10, 0) with division by zero, which will throw an ArithmeticException. We
catch this exception and print the error message.

This program demonstrates the use of the divideNumber() function and how it handles exceptions when
division by zero occurs.

You might also like