CS23D017 Oops Project

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

PROJECT REPORT

On
“Inheritance, Multithreading and
Constructor Overloading”

Submitted By:
Sachin Hanaslal Rahangdale

Guided By:
Mr. Yogesh Katre

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

S. B. JAIN INSTITUTE OF TECHNOLOGY


MANAGEMENT AND RESEARCH, NAGPUR.
(An Autonomous Institute, Affiliated to RTMNU, Nagpur)

2023-2024
© S.B.J.I.T.M.R Nagpur 2023
S.B. JAIN INSTITUTE OF TECHNOLOGY MANAGEMENT AND
RESEARCH, NAGPUR
(An Autonomous Institute, Affiliated to RTMNU, Nagpur)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SESSION 2023-2024

CERTIFICATE

This is to certify that the Project titled “Project Title” is a bonafide work of Student Name
“Sachin H. Rahangdale” carried out for the partial fulfillment of course work of “Object
Oriented Programming” , 3rd Semester, Bachelor of Technology in Computer Science &
Engineering.

Mr. Yogesh Katre Dr. Mrudula Nimbarte


Assistant Professor Head of Department
(Project Guide)

i
INDEX

CERTIFICATE i

INDEX ii

LIST OF FIGURES iii

CHAPTER 1 PROBLEM STATEMENT 1

CHAPTER 2 INTRODUCTION 2-5

CHAPTER 3 DESIGN & IMPLEMENTATION 6-16

4.1 ALGORITHM

4.2 FLOWCHART

4.3 SOURCE CODE

CHAPTER 4 RESULT 17-19


CHAPTER 5 CONCLUSION 19

REFERENCES 20

ii
LIST OF FIGURES

FIG. NO. TITLE OF FIGURE PAGE NO.

Fig.2.1 “Inheritance in Java” 3

Fig.3.2.1 “Flowchart Of 1st Problem” 9

Fig.3.2.2 “Flowchart Of 2nd Problem” 10

Fig.3.2.3 “Flowchart Of 3rd Problem” 11

Fig.5.4 “Result Of 1nd Problem” 17

Fig.5.5 “Result Of 2rd Problem” 18

Fig.5.6 “Result Of 3rd Problem” 19

iii
CHAPTER 1

PROBLEM STATEMENT

1. Define two different classes namely, Student and Employee. These


classes are derived from a base class Person. Define other two
classes Staff and Faculty. Staff and Faculty classes are derived from
Employee class. The Person class has name and age data and
display method to display the name and age of a person. The
Student class has data like rollNo and branch and display method
to display name, age, rollNo and branch of the student. Stuff has
ecNo and doj(date of joining) data and display method to display
name, age, ecNo, doj of the stuff. Faculty has designation data
(Assistant Professor, Associate Professor and Professor) and display
method to display the name, age, ecNo, doj and designation of the
Faculty. Staff has designation data (Technical and Clerical) and
display method to display the name, age, ecNo, doj and designation
of the Staff. Each class have their own constructor to initialize the
value of each data field. Finally create MainDemoClass and create
an object of each class. Print the values of all objects in the
MainDemoClass

2. Write a Java program which first generates a set of random


numbers and then determines negative, positive even, positive odd
numbers concurrently.

3. A class Shape is defined with two overloading constructors in it.


Another class Test1 is partially defined which inherits the class
Shape. The class Test1 should include two overloading constructors
as appropriate for some object instantiation shown in main()
method. You should define the constructors using the super class
constructors. Also, override the method calculate( ) in Test1 to
calculate the volume of a Shape.

1
CHAPTER 2
INTRODUCTION
1. Inheritance:-
THEORY:
Inheritance, a cornerstone of object-oriented programming (OOP), facilitates code organization and
reuse by allowing a class to inherit attributes and behaviors from another class. At its core, a base
class serves as a blueprint, encapsulating common features shared among related classes. This
establishes an "is-a" relationship, where a derived class inherits from the base class, promoting a
hierarchical structure. In this way, the derived class gains access to the existing functionality of the
base class, promoting a modular and efficient design.

The process of inheritance enables developers to create specialized classes that build upon the
foundation laid by the base class. This customization can involve adding new attributes, modifying
existing behaviors, or overriding methods. The flexibility introduced by inheritance supports
polymorphism, where objects of the derived class can be treated as instances of the base class,
promoting adaptability and code flexibility.

While inheritance offers significant benefits, it is crucial to consider design implications, such as the
potential for the "diamond problem" in multiple inheritance scenarios. This challenge highlights the
importance of careful class hierarchy planning to avoid ambiguity and ensure a clear understanding
of relationships within the system. In summary, inheritance is a powerful mechanism that enhances
code organization, promotes code reuse, and fosters the development of scalable and maintainable
software systems in OOP.

Types Of Inheritance:-

Single Inheritance:

Single inheritance in Java occurs when a class extends only one superclass. It promotes the concept
of "is-a" relationship, where a subclass is a specific type of its superclass. For example, a Dog class
can extend an Animal class, indicating that a dog is a specific type of animal.

Multiple Inheritance (through Interfaces):

While Java doesn't support multiple inheritance of classes, it allows multiple inheritance through
interfaces. An interface defines a contract, and a class can implement multiple interfaces. This
enables a class to inherit method signatures from multiple sources, promoting flexibility in design.

Multilevel Inheritance:

Multilevel inheritance involves a chain of inheritance where a class extends another class, and then
another class extends the second class. This creates a hierarchical structure, and each subclass
inherits properties and behaviors not only from its immediate superclass but also from all the
superclasses up the hierarchy.

2
Hierarchical Inheritance:

In hierarchical inheritance, multiple classes inherit from a common superclass. Each subclass
represents a specialized version of the superclass. For example, an Animal class can be the
superclass, and Dog and Cat classes can be subclasses, inheriting common characteristics from the
Animal class.

Hybrid Inheritance:

Hybrid inheritance is a combination of different types of inheritance within a single program. It can
involve a mix of single, multiple, multilevel, or hierarchical inheritance. This approach allows
developers to leverage the advantages of different inheritance types based on the requirements of the
application.

Fig.2.1 “Inheritance in java

3
2. Multithreading:-
Multithreading in Java :-
Multithreading is a programming concept where multiple threads (smaller units of a process) execute
independently but share the same resources. In Java, you can implement multithreading using the
Thread class or the Runnable interface. This project will use multithreading to concurrently analyze the
generated set of random numbers.

Random Number Generation :-


Java provides the java.util.Random class for generating random numbers. You can create an instance of
this class and use its methods to generate random integers. In your program, these random numbers will
form the basis for the subsequent analysis.

Negative, Positive Even, and Positive Odd Number Analysis:

• Negative Numbers:
• A negative number is any number less than zero. In your program, you'll iterate through the
generated random numbers and count how many are negative.

• Positive Even and Positive Odd Numbers:


• A positive even number is divisible by 2 without a remainder, while a positive odd
number is not divisible by 2. You'll concurrently count the occurrences of positive even
and positive odd numbers in the random set.

Concurrency in Java:
• Concurrency is achieved in Java through the use of threads. Each type of number analysis
(negative, positive even, positive odd) can be performed concurrently by creating and running
separate threads for each task.
• The Thread class or the Runnable interface can be utilized to create these threads. This allows
the tasks to execute independently and concurrently.

Thread Safety:
• As multiple threads are accessing shared resources (the random numbers in this case), it's crucial
to ensure thread safety. Synchronization mechanisms such as synchronized blocks or using
thread-safe data structures should be considered to prevent data corruption.

By combining these concepts, your Java program will efficiently generate random numbers and
concurrently determine the count of negative, positive even, and positive odd numbers in the set,
showcasing the power of multithreading in parallel computation.

4
3. Constructor overloading in Java:-
In Java, constructor overloading is a powerful feature that allows a class to have multiple constructors
with different parameter lists. Constructors are special methods within a class that are invoked when an
object of that class is created. Constructor overloading provides flexibility in how objects are initialized,
allowing developers to create objects in various ways based on their needs.

Key Points:

Constructors in Java:

• Constructors are special methods with the same name as the class, and they are responsible for
initializing the state of an object when it is created.
• Unlike regular methods, constructors do not have a return type.
• When an object is created using the new keyword, a constructor is called to initialize the object.
Constructor Overloading:

• Constructor overloading occurs when a class has more than one constructor with different
parameter lists.
• The constructors in an overloaded set have the same name but differ in the number or types of
parameters they accept.
• This allows objects to be created and initialized in different ways, providing flexibility to the
developer.
Advantages of Constructor Overloading:

• Flexibility: Constructor overloading provides flexibility by allowing objects to be initialized in


different ways.
• Readability: It improves code readability by providing meaningful and descriptive constructors.
• Default Values: Constructors with default values can be used to create objects with a minimal
set of parameters.

By leveraging constructor overloading, developers can create Java classes that are more versatile
and adaptable to different use cases, enhancing the overall design and usability of their code.

5
CHAPTER 3
DESIGN AND IMPLEMENTATION

3.1 ALGORITHM

Problem statement 1 (Algorithm):


Define the Person Class:
• Create a class named Person.
• Add data members for name and age.
• Include a constructor to initialize these data members.
• Implement a display method to print the name and age.

Define the Student Class:


• Inherit from the Person class.
• Add additional data members for rollNo and branch.
• Include a constructor to initialize the inherited members and new data members.
• Override the display method to include the new data members.

Define the Employee Class:


• Inherit from the Person class.
• Add additional data members for ecNo and doj (date of joining).
• Include a constructor to initialize the inherited members and new data members.
• Override the display method to include the new data members.

Define the Staff Class:


• Inherit from the Employee class.
• Add an additional data member for designation.
• Include a constructor to initialize the inherited members and the new data member.
• Override the display method to include the new data member.

Define the Faculty Class:


• Inherit from the Employee class.
• Add an additional data member for designation.
• Include a constructor to initialize the inherited members and the new data member.
• Override the display method to include the new data member.

Define the MainDemoClass:


• Create an object of the Person class and print its details using the display method.
• Create an object of the Student class and print its details using the display method.
• Create an object of the Staff class and print its details using the display method.
• Create an object of the Faculty class and print its details using the display method.

6
Problem statement 2 (Algorithm):

Generate Random Numbers:


• Define a function generateRandomNumbers that takes an integer count as input.
• Inside the function, initialize an array randomNumbers to store the generated numbers.
• Use a loop to generate count random integers and store them in the array. These numbers can be
generated within a specific range, for example, between -100 and 100.

Number Analysis Task:


• Create a class NumberAnalyzer that extends the Thread class.
• Inside the class, define data members to store a chunk of random numbers, as well as counters
for negative, positive even, and positive odd numbers.
• Implement a constructor that takes the chunk of numbers as a parameter.
• Override the run method to analyze the numbers in the chunk.
• Within the run method, iterate through the chunk and increment the counters based on whether
the number is negative, positive even, or positive odd.

Main Program:
• In the main program, generate a set of random numbers using the generateRandomNumbers
function.
• Specify the number of threads (numThreads) to be used for concurrent analysis.
• Split the array of random numbers into equal parts based on the number of threads.
• Create instances of the NumberAnalyzer class for each chunk.
• Create an array of threads to hold the instances of NumberAnalyzer.
• Start each thread, which will concurrently analyze its assigned chunk of numbers.
• Wait for all threads to complete using the join method.
• Collect and combine the results from each analyzer.
• Display the total count of negative, positive even, and positive odd numbers in the entire set

This algorithm outlines the steps to generate random numbers, create a concurrent analysis task using
multithreading, and then combine the results for further processing.

7
Problem statement 3 (Algorithm):
Define the Shape Class:
• Define a class named Shape.
• Include two overloading constructors in the Shape class.
• Constructor 1: Takes parameters to initialize properties related to the shape.
• Constructor 2: Default constructor with no parameters.

Define the Test1 Class:


• Create a class named Test1 that inherits from the Shape class.
• Include two overloading constructors in Test1 class:
• Constructor 1: Calls the corresponding constructor in the superclass (Shape) using the super
keyword and initializes additional properties specific to Test1.
• Constructor 2: Default constructor that calls the default constructor in the superclass (Shape)
using the super keyword.

Override the calculate Method:


• Inside the Test1 class, override the calculate method inherited from the Shape class.
• Implement the overridden calculate method to calculate the volume of the shape. The exact
calculation will depend on the type of shape and properties.

Main Method:
• In the main method:
• Instantiate objects of the Test1 class using both constructors.
• Call the calculate method on each object to calculate the volume.

8
3.2 FLOWCHART

Problem statement 1 (Flowchart):

Fig.3.2.1 “Flowchart Of 1st Problem”


9
Problem statement 2 (Flowchart):

Fig.3.2.2 “Flowchart Of 2nd Problem”

10
Problem statement 3 (Flowchart):

Fig.3.2.3 “Flowchart Of 3rd Problem”

11
3.3 SOURCE CODE

Problem statement 1 (Source Code):


// Name : Sachin H. Rahangdale
//USN No. : CS23D017

import java.util.Date;

class Person {
String name;
int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void display() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

class Employee extends Person {


public Employee(String name, int age) {
super(name, age);
}
}

class Student extends Person {


int rollNo;
String branch;

public Student(String name, int age, int rollNo, String branch) {


super(name, age);
this.rollNo = rollNo;
this.branch = branch;
}

public void display() {


super.display();
System.out.println("Roll No: " + rollNo);
System.out.println("Branch: " + branch);
}
}

class Staff extends Employee {


int ecNo;
Date doj;
String designation;
12
public Staff(String name, int age, int ecNo, Date doj, String designation) {
super(name, age);
this.ecNo = ecNo;
this.doj = doj;
this.designation = designation;
}

public void display() {


super.display();
System.out.println("Employee Code No: " + ecNo);
System.out.println("Date of Joining: " + doj);
System.out.println("Designation: " + designation);
}
}

class Faculty extends Employee {


int ecNo;
Date doj;
String designation;

public Faculty(String name, int age, int ecNo, Date doj, String designation) {
super(name, age);
this.ecNo = ecNo;
this.doj = doj;
this.designation = designation;
}

public void display() {


super.display();
System.out.println("Employee Code No: " + ecNo);
System.out.println("Date of Joining: " + doj);
System.out.println("Designation: " + designation);
}
}

public class MainDemoClass {


public static void main(String[] args) {
Student student = new Student("John Doe", 20, 12345, "Computer Science");
Staff staff = new Staff("Jane Smith", 30, 56789, new Date(), "Technical");
Faculty faculty = new Faculty("Dr. James Brown", 40, 98765, new Date(), "Professor");

System.out.println("Student Information:");
student.display();
System.out.println("\nStaff Information:");
staff.display();
System.out.println("\nFaculty Information:");
faculty.display();
}
}

13
Problem statement 2 (Source Code):
// Name : Sachin H. Rahangdale
//USN No. : CS23D017
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class NumberClassifier implements Runnable {


private final int[] numbers;
private final String type;

public NumberClassifier(int[] numbers, String type) {


this.numbers = numbers;
this.type = type;
}

@Override
public void run() {
switch (type) {
case "negative":
classifyNegative();
break;
case "even":
classifyEven();
break;
case "odd":
classifyOdd();
break;
}
}

private void classifyNegative() {


System.out.println("Negative Numbers:");
for (int num : numbers) {
if (num < 0) {
System.out.print(num + " ");
}
}
System.out.println();
}

private void classifyEven() {


System.out.println("Positive Even Numbers:");
for (int num : numbers) {
if (num > 0 && num % 2 == 0) {
System.out.print(num + " ");
}
}
System.out.println();
}

14
private void classifyOdd() {
System.out.println("Positive Odd Numbers:");
for (int num : numbers) {
if (num > 0 && num % 2 != 0) {
System.out.print(num + " ");
}
}
System.out.println();
}
}

public class Program3 {


public static void main(String[] args) {
int[] numbers = generateRandomNumbers(10);

System.out.println("Generated Numbers:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();

ExecutorService executorService = Executors.newFixedThreadPool(3);

executorService.submit(new NumberClassifier(numbers, "negative"));


executorService.submit(new NumberClassifier(numbers, "even"));
executorService.submit(new NumberClassifier(numbers, "odd"));

executorService.shutdown();
}

private static int[] generateRandomNumbers(int count) {


int[] numbers = new int[count];
Random random = new Random();
for (int i = 0; i < count; i++) {
numbers[i] = random.nextInt(201) - 100; // Generating random numbers between -100 and 100
}
return numbers;
}
}

15
Problem statement 3 (Source Code):
// Name : Sachin Rahangdale
//USN No. : CS23D017
class Shape {
double length, width;

Shape(double length, double width) {


this.length = length;
this.width = width;
}

Shape(double side) {
this.length = side;
this.width = side;
}

double calculate() {
return length * width;
}
}

class Test1 extends Shape {


double height;

Test1(double length, double width, double height) {


super(length, width);
this.height = height;
}

Test1(double side, double height) {


super(side);
this.height = height;
}

@Override
double calculate() {
return length * width * height;
}
}

public class Main {


public static void main(String[] args) {
Test1 test1A = new Test1(5.0, 3.0, 2.0);
Test1 test1B = new Test1(4.0, 3.0);

System.out.println("Volume of test1A: " + test1A.calculate());


System.out.println("Volume of test1B: " + test1B.calculate());
}
}

16
CHAPTER 5
RESULT
Problem statement 1 (Result):

Fig.5.2 “Result Of 1st Problem’’

17
Problem statement 2 (Result):

Fig.5.4 “Result Of 2nd Problem”

18
Problem statement 3 (Result):

Fig.5.6 “Result Of 3rd Problem”

19
CHAPTER 6
CONCLUSION

In conclusion, this microproject has provided a comprehensive exploration of key object-


oriented programming concepts, with a particular emphasis on inheritance,
multithreading, and constructor overloading. Through the implementation of a practical
application, we have demonstrated the power and versatility of these concepts in real-
world scenarios.

Inheritance has proven to be a valuable mechanism for creating a hierarchy of classes,


allowing for code reuse and the establishment of a clear and organized structure. By
inheriting attributes and behaviors from a base class, we can achieve a modular and
extensible design that enhances maintainability.

The integration of multithreading into our project has brought forth the advantages of
concurrent execution. Through the use of threads, we have improved the efficiency of
our application by allowing multiple tasks to run concurrently. This not only enhances
performance but also provides a more responsive and dynamic user experience.

Constructor overloading has played a pivotal role in tailoring the initialization process of
our objects to meet diverse requirements. The ability to create multiple constructors with
varying parameter lists has granted flexibility and adaptability to our codebase, ensuring
that objects can be instantiated in different ways to suit specific needs.

As we reflect on the challenges and triumphs encountered during the development of this
microproject, it becomes evident that a solid understanding of these fundamental
concepts is crucial for building robust and scalable software solutions. The synergy
between inheritance, multithreading, and constructor overloading has empowered us to
create a well-structured and efficient application that can evolve to meet future demands.

In the ever-evolving landscape of software development, the knowledge gained from this
microproject serves as a foundation for tackling more complex challenges and exploring
advanced topics. The journey through inheritance, multithreading, and constructor
overloading has not only enhanced our coding skills but has also deepened our
appreciation for the elegance and power of object-oriented programming principles. As
we continue on our programming endeavors, these concepts will undoubtedly remain
essential tools in our toolkit for crafting high-quality and maintainable software
solutions.

20
REFERENCE

[1] www.w3school.com
[2] www.geekforgeeks.org
[3] Java Programming Book by TechMax
[4] www.tutorialspoint.com
[5] www.youtube.com
[6] www.code2flow.com

21

You might also like