Os Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

MC:307 OBJECT ORIENTED PROGRAMMING

LAB MANUAL
BACHELOR OF TECHNOLOGY
IN
Mathematics and Computing

SUBMITTED BY :
Aditya Harsh (2K20/MC/12)

UNDER THE SUPERVISION OF :

Prof. Aditya Kaushik


and
Ms. Shivani Jain

DEPARTMENT OF APPLIED MATHEMATICS


DELHI TECHNOLOGICAL UNIVERSITY (Formerly Delhi College of Engineering)
Bawana Road, Delhi-110042
OCTOBER 2023
INDEX

S.NO Date Program Signature

1 11/08/23 Create a class named “Time” in C++ with three data


members namely hour, minute and seconds. Create two
member functions of the class namely “setTime” that sets
the hour, minute and seconds for any object; and “print”
function that prints the hour, minute, and seconds value for
the object. Test the class by creating its two objects in main.

2 18/08/23 Write a program in C++ demonstrating the use of


constructor (with no arguments), constructor (with
parameterized arguments) and destructor. Create objects
of that class in main and test those objects with these
constructors and destructor function.

3 25/08/23 Write a C++ program illustrating the operator overloading


of binary operators (addition and subtraction), and unary
operators (prefix and postfix increment).

4 01/09/23 Implement inheritance in C++ program. Create a base class


named Person (with data members first_name, and
last_name). Derive a class named Employee from base class
Person. The Employee class should include a data member
named employee_id. Further a class named Manager
should be derived from the class Employee and the
Manager class should include two data members named
employee_designation and employee_salary. Create at least
three objects of class Manager, specify the values of all their
attributes, and determine which manager has the highest
salary.

5 08/09/23 Write a program in C++ demonstrating class templates.

6 15/09/23 Write a program in C++ demonstrating rethrowing an


exception.

7 15/09/23 Create an inheritance hierarchy (any inheritance example


of your choice) in JAVA. Create one super class and three
sub classes should inherit from that super class. Also
highlight the concept of function overriding and function
overloading in your program.
8 22/09/23 Write a JAVA program explaining the working of
constructors along with the super keyword.

9 06/10/23 Write a Java program consisting of abstract classes and


abstract method(s). The first concrete sub class in the
inheritance hierarchy must implement the abstract
method(s). Create the objects of the concrete class and test
your program.

10 12/10 Write a Java program explaining the working of static


methods in a class.
Experiment 1
Aim: Create a class named “Time” in C++ with three data members namely hour, minute
and seconds. Create two member functions of the class namely “setTime” that sets the
hour, minute and seconds for any object; and “print” function that prints the hour, minute,
and seconds value for the object. Test the
class by creating its two objects in main.

Objective : The aim is to make students learn how to create classes and their objects in
an object oriented program. Students also learn how the member function can be defined
within a class and how an object can call the member function of its class from the main
function with an dot operator.

Software/ Resources used : C++ programming language

Procedure/ Methodology :

1. Create a class “Time” with data members and member functions as written in the aim
of the practical.
2. Create two objects of the class “Time” inside the main function using the syntax:
“Time obj1, obj2”.
3. Set the data members for each of the object with the help of dot operator, i.e., call the
member function, say obj1.setTime, and set the data members for both the objects.
4. Call the print function from the object(s) defined inside the main function with the help
of dot operator to print its hour, minute and seconds.
CODE:
#include <iostream>

class Time {
private:
int hour;
int minute;
int seconds;

public:
// Member function to set the time
void setTime(int h, int m, int s) {
hour = h;
minute = m;
seconds = s;
}

// Member function to print the time


void print() {
std::cout << "Time: " << hour << ":" << minute << ":" << seconds
<< std::endl;
}
};

int main() {
// Create two objects of the Time class
Time obj1, obj2;

// Set the time for obj1


obj1.setTime(9, 30, 45);

// Set the time for obj2


obj2.setTime(12, 15, 0);

// Print the times for both objects


obj1.print();
obj2.print();

return 0;
}
OUTPUT:
Experiment 2
Aim: Write a program in C++ demonstrating the use of constructor (with no
arguments), constructor (with parameterized arguments) and destructor. Create objects
of that class in main and test those objects with these constructors and destructor
function.
Objective : The aim is to make students learn how to create constructors and destructor
functions inside a class. Students also learn how any object of the class allocates its
memory and de-allocates its memory after calling the constructor and destructor function
respectively.

Software/ Resources used : C++ programming language

Procedure/ Methodology :
1. Create any class in C++ with some data members, member functions and a
constructor (with parameters and without parameters) and a destructor
function.
2. Call the constructor function to set the data members for the object from the
main. Use the dot operator to call the constructor.
3. Call any member function to verify the values for the data members set by
the constructor.
4. Call the destructor to de-allocate the memory reserved by the object of the
class. Use the dot operator to call the destructor.
CODE:
#include <iostream>

class MyClass {
private:
int value;

public:
// Constructor with no arguments
MyClass() {
std::cout << "Constructor with no arguments called." << std::endl;
value = 0;
}

// Constructor with parameterized arguments


MyClass(int val) {
std::cout << "Parameterized constructor called." << std::endl;
value = val;
}

// Destructor
~MyClass() {
std::cout << "Destructor called." << std::endl;
}

void display() {
std::cout << "Value: " << value << std::endl;
}
};

int main() {
// Create objects of the class
MyClass obj1; // Constructor with no arguments called
MyClass obj2(42); // Parameterized constructor called

// Call member function to display values


obj1.display(); // Value: 0
obj2.display(); // Value: 42

// Destructor will be automatically called when objects go out of


scope
return 0;
}
Experiment 3

Aim: Write a C++ program illustrating the operator overloading of binary


operators (addition and subtraction), and unary operators (prefix and postfix
increment).

Objective : The aim is to make students learn how operator overloading works in
object oriented programming. Students also learn two methods of operator
overloading: one with friend function, and other without friend function.
Software/ Resources used : C++ programming language

Procedure/ Methodology :
1. Create any class in C++ with some data members, member functions and
some operator functions that are to be overloaded.
2. Create one friend function of the class. Use this friend function to overload
binary and unary operators.
3. Create objects of that class inside main function. Call the operator functions
(friend functions and non-friend member functions) with the dot operator
from the objects of that class.
4. Observe the behavior of the overloaded functions and analyze how those
operators can be customized to work with objects of any class.
CODE:
#include <iostream>

class MyClass {
private:
int value;

public:
MyClass(int val) : value(val) {}

// Binary operator overloading (non-friend member functions)


MyClass operator+(const MyClass& other) {
return MyClass(this->value + other.value);
}

MyClass operator-(const MyClass& other) {


return MyClass(this->value - other.value);
}

// Unary operator overloading (prefix increment)


MyClass& operator++() {
++value;
return *this;
}

// Unary operator overloading (postfix increment)


MyClass operator++(int) {
MyClass temp(*this);
++value;
return temp;
}

void display() {
std::cout << "Value: " << value << std::endl;
}

// Friend function for operator overloading


friend MyClass operator-(const MyClass& obj);
};

// Friend function for unary operator overloading (negation)


MyClass operator-(const MyClass& obj) {
return MyClass(-obj.value);
}

int main() {
MyClass obj1(10);
MyClass obj2(5);

// Binary operator overloading with member functions


MyClass result_add = obj1 + obj2;
MyClass result_sub = obj1 - obj2;

// Unary operator overloading (prefix increment) with member function


++obj1;

// Unary operator overloading (postfix increment) with member function


obj2++;

// Unary operator overloading (negation) with friend function


MyClass result_neg = -obj1;

// Display the results


std::cout << "Result of addition: ";
result_add.display();

std::cout << "Result of subtraction: ";


result_sub.display();

std::cout << "Prefix Increment of obj1: ";


obj1.display();

std::cout << "Postfix Increment of obj2: ";


obj2.display();

std::cout << "Negation of obj1: ";


result_neg.display();

return 0;
}
Experiment 4

Aim: Implement inheritance in C++ program. Create a base class named Person (with
data members first_name, and last_name). Derive a class named Employee from base
class Person. The Employee class should include a data member named employee_id.
Further a class named Manager should be derived from the class Employee and the
Manager class should include two data members named employee_designation and
employee_salary. Create at least three objects of class Manager, specify the values of all
their attributes, and determine which manager has the highest salary.

Objective: The aim is to make students learn how inheritance works in C++. Students
also learn how to create child classes from the parent class, relationship between the child
and parent class and how objects of child class interact with parent class.

Software/ Resources used : C++ programming language

Procedure/ Methodology :
1. Create any class in C++ with some data members and member functions.
2. Create a child class from the above defined parent class using public inheritance, i.e.,
use public keyword while inheriting the parent class.
3. For the child class, inherit the public members from the parent class, and create some
extra data members specific to the child class which are not present in the parent class.
4. Create objects of both parent and child classes inside the main function.
5. For both types of objects, call their corresponding member functions from the main
function with the dot operator.
CODE:

#include <iostream>
#include <string>

class Person {
protected:
std::string first_name;
std::string last_name;

public:
Person(const std::string& first, const std::string& last)
: first_name(first), last_name(last) {}

void display() {
std::cout << "Name: " << first_name << " " << last_name <<
std::endl;
}
};

class Employee : public Person {


protected:
int employee_id;

public:
Employee(const std::string& first, const std::string& last, int id)
: Person(first, last), employee_id(id) {}

void display() {
Person::display();
std::cout << "Employee ID: " << employee_id << std::endl;
}
};

class Manager : public Employee {


private:
std::string employee_designation;
double employee_salary;

public:
Manager(const std::string& first, const std::string& last, int id,
const std::string& designation, double salary)
: Employee(first, last, id), employee_designation(designation),
employee_salary(salary) {}

void display() {
Employee::display();
std::cout << "Designation: " << employee_designation << std::endl;
std::cout << "Salary: $" << employee_salary << std::endl;
}

double getSalary() {
return employee_salary;
}
};

int main() {
Manager manager1("John", "Doe", 101, "Senior Manager", 75000.0);
Manager manager2("Jane", "Smith", 102, "Assistant Manager", 60000.0);
Manager manager3("Bob", "Johnson", 103, "Manager", 80000.0);

// Display information for all three managers


manager1.display();
std::cout << "----------------------" << std::endl;
manager2.display();
std::cout << "----------------------" << std::endl;
manager3.display();
std::cout << "----------------------" << std::endl;

// Determine the manager with the highest salary


if (manager1.getSalary() >= manager2.getSalary() &&
manager1.getSalary() >= manager3.getSalary()) {
std::cout << "Manager 1 has the highest salary." << std::endl;
} else if (manager2.getSalary() >= manager1.getSalary() &&
manager2.getSalary() >= manager3.getSalary()) {
std::cout << "Manager 2 has the highest salary." << std::endl;
} else {
std::cout << "Manager 3 has the highest salary." << std::endl;
}

return 0;
}
Experiment 5

Aim: Write a program in C++ demonstrating class templates.

Objective : The aim is to make students learn the concept of templates in object
oriented programming, i.e. with general class templates, customized classes of integers,
floats, or any other data type can be created at run-time.

Software/ Resources used : C++ programming language

Procedure/ Methodology :
1. Create a general class template <T> in C++ with some data members and
member functions of type <T>.
2. Customize the class template <T> with integer, create an integer class at
run-time, and test the member functions of that class with integer objects
from the main function.
3. Customize the class template <T> with floats, create a float class at run-
time, and test the member functions of that class with float objects from the
main function.
4. Customize the class template <T> with character data type, create a
character type class at run-time, and test the member functions of that class
with character objects from the main function.
Conclusion: With this practical, students can learn the concept of class templates,
i.e., how general class templates <T> can be customized specifically to work with
integers, floats or any other data type at run time.
CODE:

#include <iostream>
#include <string>

// Create a generic class template for a pair of values


template <typename T1, typename T2>
class Pair {
private:
T1 first;
T2 second;

public:
Pair(T1 val1, T2 val2) : first(val1), second(val2) {}

void display() {
std::cout << "Pair: " << first << ", " << second << std::endl;
}
};

int main() {
// Create a Pair for integers
Pair<int, int> intPair(10, 20);
std::cout << "Integer Pair:" << std::endl;
intPair.display();

// Create a Pair for floats


Pair<float, float> floatPair(3.14f, 2.71f);
std::cout << "Float Pair:" << std::endl;
floatPair.display();

// Create a Pair for strings


Pair<std::string, std::string> stringPair("Hello", "World");
std::cout << "String Pair:" << std::endl;
stringPair.display();

return 0;
}
Experiment 6

Aim: Write a program in C++ demonstrating rethrowing an exception.

Objective : The aim is to make students learn the concept of exception handling, and
how the exceptions can be handled at various levels, i.e., handling the exceptions at first
catch block, or rethrowing it and further catching it at next try - catch block.

Software/ Resources used : C++ programming language

Procedure/ Methodology :
1. Create any class with some data members and member functions.
2. Create a try-catch block with some parameters, say divide by zero or
overflow condition.
3. Throw an exception from the try block and catch that exception with its
corresponding catch block.
4. Then, throw a different exception from the try block, do not catch that
exception in the first catch block, rather rethrow the same exception from
its catch block so that it is handled by the next try – catch block, thus
implementing the concept of rethrowing an exception.
CODE:
#include <iostream>
#include <cassert>

class MyException {
public:
MyException(const char* message) : message_(message) {}

const char* what() const {


return message_;
}

private:
const char* message_;
};

int divide(int numerator, int denominator) {


if (denominator == 0) {
throw MyException("Division by zero is not allowed.");
}
return numerator / denominator;
}

int main() {
try {
// Test case 1: Division by non-zero denominator
int result = divide(10, 2);
assert(result == 5);
std::cout << "Test case 1: Result = " << result << std::endl;
} catch (const MyException& e) {
std::cerr << "Test case 1: Caught an exception: " << e.what() <<
std::endl;
}

try {
// Test case 2: Division by zero
int result = divide(10, 0);
std::cout << "Test case 2: Result = " << result << std::endl;
} catch (const MyException& e) {
std::cerr << "Test case 2: Caught an exception: " << e.what() <<
std::endl;
} catch (...) {
std::cerr << "Test case 2: Caught an unknown exception." << std::endl;
}

return 0;
}
Experiment 7
Aim: Create an inheritance hierarchy (any inheritance example of your choice) in JAVA.
Create one super class and three sub classes should inherit from that super class. Also
highlight the concept of function overriding and function overloading in your program.

Objective: The aim is to make students learn the concept of super class and sub classes
in Java programming. Students also learn the difference between function overloading
and function overriding in object oriented programming.
Software/ Resources used : Java programming language
Procedure/ Methodology :

1. Create any class in Java with some data members and member functions.
2. Inherit three sub classes from the above defined super class with public
inheritance.
3. Create two functions with same name in the super class and implement function
overloading with difference in terms of number or type of arguments.
4. Create two functions with same name, one in super class and other in sub class,
and implement function overriding by calling the super class member function and
sub class member function from the sub class object defined within the main
function.
5. Test member functions of super and sub classes by creating objects of these classes
inside the main function.
CODE:

class Shape {
protected String name;

public Shape(String name) {


this.name = name;
}

public void display() {


System.out.println("Shape: " + name);
}

public void calculateArea() {


System.out.println("Calculating area for a generic shape");
}

public void calculatePerimeter() {


System.out.println("Calculating perimeter for a generic shape");
}
}

class Circle extends Shape {


private double radius;

public Circle(String name, double radius) {


super(name);
this.radius = radius;
}

@Override
public void calculateArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of " + name + " (Circle): " + area);
}

@Override
public void calculatePerimeter() {
double perimeter = 2 * Math.PI * radius;
System.out.println("Perimeter of " + name + " (Circle): " + perimeter);
}
}

class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(String name, double width, double height) {


super(name);
this.width = width;
this.height = height;
}

@Override
public void calculateArea() {
double area = width * height;
System.out.println("Area of " + name + " (Rectangle): " + area);
}

@Override
public void calculatePerimeter() {
double perimeter = 2 * (width + height);
System.out.println("Perimeter of " + name + " (Rectangle): " + perimeter);
}
}

class Triangle extends Shape {


private double base;
private double height;

public Triangle(String name, double base, double height) {


super(name);
this.base = base;
this.height = height;
}

@Override
public void calculateArea() {
double area = 0.5 * base * height;
System.out.println("Area of " + name + " (Triangle): " + area);
}

// Overloading the calculatePerimeter method


public void calculatePerimeter(double side1, double side2, double side3) {
double perimeter = side1 + side2 + side3;
System.out.println("Perimeter of " + name + " (Triangle): " + perimeter);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Circle circle = new Circle("Circle A", 5.0);
Rectangle rectangle = new Rectangle("Rectangle B", 4.0, 6.0);
Triangle triangle = new Triangle("Triangle C", 3.0, 4.0);

circle.display();
circle.calculateArea();
circle.calculatePerimeter();

rectangle.display();
rectangle.calculateArea();
rectangle.calculatePerimeter();

triangle.display();
triangle.calculateArea();
triangle.calculatePerimeter(3.0, 4.0, 5.0); // Overloaded method with
different arguments
}
}

OUTPUT:
EXPERIMENT 8

Aim: Write a JAVA program explaining the working of constructors along with the
super keyword.

Objective : The aim is to make students learn the concept of constructors in Java
programming. Students also learn the concept of Super keyword in Java, i.e., how super
class constructor and methods can be called from the sub class with Super keyword.

Software/ Resources used : Java programming language


Procedure/ Methodology :

1. Create any class in Java with some data members and member functions.
2. Inherit a sub class from the above defined super class with public inheritance.
3. Create constructor for both sub class and super class.
4. Call the constructor of the super class from the sub class constructor.
5. Now, apply the Super keyword and then call the constructor of the super class from
the sub class constructor and observe the differences.
6. Test member functions of super and sub classes by creating objects of these classes
inside the main function.

// Abstract class with an abstract method


abstract class Shape {
protected String name;

public Shape(String name) {


this.name = name;
}

// Abstract method to calculate area


public abstract double calculateArea();

public void display() {


System.out.println("Shape: " + name);
}
}

// Concrete subclass that implements the abstract method


class Circle extends Shape {
private double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

// Another concrete subclass


class Rectangle extends Shape {
private double width;
private double height;

public Rectangle(String name, double width, double height) {


super(name);
this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Circle circle = new Circle("Circle A", 5.0);
Rectangle rectangle = new Rectangle("Rectangle B", 4.0, 6.0);

// Display and calculate area for the circle


circle.display();
double circleArea = circle.calculateArea();
System.out.println("Area of " + circle.name + ": " + circleArea);

// Display and calculate area for the rectangle


rectangle.display();
double rectangleArea = rectangle.calculateArea();
System.out.println("Area of " + rectangle.name + ": " + rectangleArea);

// Attempt to create an object of the abstract class (not allowed)


// Shape shape = new Shape("Abstract Shape"); // This will result in a
compilation error
}
}
EXPERIMENT 9

Aim: Write a Java program consisting of abstract classes and abstract method(s). The
first concrete sub class in the inheritance hierarchy must implement the abstract
method(s). Create the objects of the concrete class and test your program.
Objective : The aim is to make students learn the concept of abstract classes and
abstract methods in Java. Students also learn the difference between concrete class and
abstract class in object oriented programming and how abstract methods of abstract
classes can be overridden in non-abstract sub classes.
Software/ Resources used : Java programming language
Procedure/ Methodology :

1. Create any abstract class in Java with some data members and abstract member
functions.
2. Inherit two sub classes from the above defined super class with public inheritance,
one with abstract keyword and other without abstract keyword.
3. Override the abstract method of the super class in the non abstract sub class.
4. Create objects of non abstract classes and call their corresponding methods.
5. Try to create objects of abstract classes and analyze the difference between abstract
classes and concrete classes.

// Abstract class with an abstract method


abstract class Shape {
protected String name;

public Shape(String name) {


this.name = name;
}

// Abstract method to calculate area


public abstract double calculateArea();

public void display() {


System.out.println("Shape: " + name);
}
}

// Concrete subclass that implements the abstract method


class Circle extends Shape {
private double radius;

public Circle(String name, double radius) {


super(name);
this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

// Another concrete subclass


class Rectangle extends Shape {
private double width;
private double height;

public Rectangle(String name, double width, double height) {


super(name);
this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}
}

public class AbstractClass {


public static void main(String[] args) {
Circle circle = new Circle("Circle A", 5.0);
Rectangle rectangle = new Rectangle("Rectangle B", 4.0,
6.0);
// Display and calculate area for the circle
circle.display();
double circleArea = circle.calculateArea();
System.out.println("Area of " + circle.name + ": " +
circleArea);

// Display and calculate area for the rectangle


rectangle.display();
double rectangleArea = rectangle.calculateArea();
System.out.println("Area of " + rectangle.name + ": " +
rectangleArea);

// Attempt to create an object of the abstract class


(not allowed)
// Shape shape = new Shape("Abstract Shape"); // This
will result in a compilation error
}
}
EXPERIMENT 10

Aim: Write a Java program explaining the working of static methods in a class.

Objective : The aim is to make students learn the concept of static and non-static
methods and data members. Students learn how one copy of static data member is shared
by all objects of a class as compared to non static members, which every object has its
own copy of.

Software/ Resources used : Java programming language

Procedure/ Methodology :

1. Create any class in Java with some data members and member functions.
2. Create some members and methods as static and some as non-static.
3. Define the body of static method with static data members.
4. Call the static and non-static member functions from the objects of the class
created inside the main function.
5. Change the value of static data member from different objects and observe how
one copy of static data member is shared by all objects of the class.
class MyClass {
// Static data member shared by all objects
static int staticVariable = 0;

// Non-static data member, each object has its own copy


int nonStaticVariable;

// Static method that operates on the static data member


static void incrementStaticVariable() {
staticVariable++;
}

// Non-static method
void setNonStaticVariable(int value) {
nonStaticVariable = value;
}

// Non-static method to display both static and non-static variables


void displayVariables() {
System.out.println("Static Variable: " + staticVariable);
System.out.println("Non-Static Variable: " + nonStaticVariable);
}
}

public class StaticMethod {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

// Calling the static method to increment the static variable


MyClass.incrementStaticVariable();

// Setting non-static variables for obj1 and obj2


obj1.setNonStaticVariable(10);
obj2.setNonStaticVariable(20);

// Displaying variables for obj1 and obj2


System.out.println("Variables for obj1:");
obj1.displayVariables();
System.out.println();

System.out.println("Variables for obj2:");


obj2.displayVariables();
System.out.println();

// Change the value of static data member


MyClass.staticVariable = 100;

// Display variables again


System.out.println("After changing static variable:");
System.out.println("Variables for obj1:");
obj1.displayVariables();
System.out.println();

System.out.println("Variables for obj2:");


obj2.displayVariables();
}
}

OUTPUT:
EXPERIMENT 11

Aim: Write a Java program implementing Swing Applet.


Objective : The aim is to make students learn the concept of applets, which run on the
browser and downloaded on demand, and swings which are the collection of user
interface components in Java programming.
Software/ Resources used : Java programming language
Procedure/ Methodology :

1. Create any class in Java that inherits Applet in built class and implements the
interface of Action Listener.
2. Create some text fields, labels, buttons and JLabel in the class.
3. Set their corresponding names and labels for those text fields and buttons.
4. Set their foreground and background colors, if required.
5. Run the Java program and observe the output in Java enabled web browser.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy