0% found this document useful (0 votes)
48 views

Laboratory Manual _cse 2104 (2)

The document is a laboratory manual for the CSE 2104 Object Oriented Programming Lab, detailing the principles of OOP, course objectives, and outcomes. It includes lab sheets with objectives, problems, and solutions for practical exercises involving Java programming concepts such as classes, objects, constructors, and user input. Additionally, it provides practice problems to reinforce learning and understanding of Java OOP principles.

Uploaded by

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

Laboratory Manual _cse 2104 (2)

The document is a laboratory manual for the CSE 2104 Object Oriented Programming Lab, detailing the principles of OOP, course objectives, and outcomes. It includes lab sheets with objectives, problems, and solutions for practical exercises involving Java programming concepts such as classes, objects, constructors, and user input. Additionally, it provides practice problems to reinforce learning and understanding of Java OOP principles.

Uploaded by

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

LABORATORY MANUAL

Course No.: CSE 2104


Course Title: Object Oriented Programming Lab
Introduction

OOP (Object-Oriented Programming):


OOP is a programming paradigm that allows you to organize and structure your code around
objects and classes. It provides a set of principles and techniques to design and implement
software systems. Here are the properties, objectives, prerequisites, and learning outcomes of
learning Java OOP:

Properties of Java OOP:


Encapsulation: Objects encapsulate data and behaviors, hiding the internal details and providing
a clean interface for interacting with the object.
Inheritance: Classes can inherit properties and behaviors from other classes, promoting code
reuse and creating a hierarchical relationship between classes.
Polymorphism: Objects can take on different forms or have multiple behaviors depending on the
context in which they are used.
Abstraction: Abstract classes and interfaces allow the programmer to define common
characteristics and behaviors for a group of related classes.

Course Objectives:
● Recognize Java in terms of OOP
● Understand the relationship between Class, Object, Abstraction, Interface and
Polymorphism
● Develop basic problem-solving skills, produce quality code, know best practices
● Trace code and infer issues to handle exceptions
● Interpret and analyze problem to design an Enterprise solution

Course Outcomes:
1. Demonstrate the fundamental concepts of object-oriented programming
2. Apply the concepts of object-oriented programming for solving real-world problems
LAB Sheet #1
OBJECTIVES:
i. Getting acquainted with JDK and Netbeans IDE
ii. Writing the first Java program using Netbeans IDE
iii. To be familiar with the basic concept of class and object

PROBLEM
a. Install JDK and Netbeans. Create a Java with Maven project. Write your first java program
to print ‘Hello World’.
b. Create a student class with properties id, name, email, cgpa, hometown. Create two
objects for the class. Finally display the details of those objects using various techniques.
Solution:
a. Install JDK and Netbeans using the following video tutorial:

https://www.youtube.com/watch?v=vt7_6HwCFOU

Writing first Java program using netbeans:

Take the steps below to set up a new Java project.

1. In the IDE, choose File > New Project or click the "New Project" button in the toolbar.
2. In the New Project wizard, select Java Application, as shown in the figure below. Then click
Next.

3. In the Name and Location page of the wizard, type HelloWorld in the Project Name field,
(as shown in the figure below):
4. Click Finish. The project is created and opened.

5. Click the play icon (Run Project). You should have the output window like this.
b. Create a student class with properties id, name, email, cgpa, hometown. Create two
objects for the class. Finally display the details of those objects using various techniques.

Prerequisites:
i. Basic knowledge of Java programming language.
ii. Understanding of classes, objects, and constructors in Java.

Learning outcomes:
i. Understanding how to create a class with properties and methods in Java.
ii. Understanding how to create objects and set their properties.
iii. Understanding how to access and display object properties.

Problem Analysis:
we need to create a Student class with properties such as id, name, email, cgpa, and hometown.
Then, we need to create two objects of the Student class and display their details using methods
and without using methods.

Background Theory:
Classes in Java:
It is a blueprint or template for creating objects.
 Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of methods.

Objects in Java:
It is a basic unit of Object-Oriented Programming and represents real-life entities. An object
consists of:

 State: It is represented by attributes of an object. It also reflects the properties of an


object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object with other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.

The problem is to create a Student class in Java with properties such as id, name, email, cgpa,
and hometown. Two objects of the class need to be created, initializing the properties one by
one using the objects. Finally, the details of those objects should be displayed using various
techniques.

Algorithm Design:
1. Create a Java class named "Student" with properties: id (integer), name (string), email
(string), cgpa (double), and hometown (string).
2. Write a display method to display the properties for a student object.
3. In the main method:
a. Create two Student objects.
b. Initialize the properties of the two objects.
4. Display the details of the first object without using the display method.
5. Display the details of the second object using the display method.

Code:

Figure 1: Class with properties and method


Figure 2: Main method

Figure 3: Output
Practice Problems
1. Create a class called BankAccount with instance variables accountNumber and
balance. Add methods to deposit and withdraw money from the account. Create
objects of BankAccount and perform deposit and withdrawal operations.
2. Create a class rectangle with properties such as length and width. Add methods to
calculate the perimeter and area of the rectangle. Create objects and display their
corresponding perimeter and area.
3. Create a class called movie which as properties such as title, genre, leadactor,
director, release year, rating and review. Create two movie objects and display their
properties. If the rating is <5, the review should be “Not Good”. Otherwise, the
review would be “Good”.
LAB Sheet #2
OBJECTIVES:
i. To be familiar with parameterized constructor
ii. To be familiar with the static keyword
iii. To be familiar with the difference between class properties/methods and object
properties and methods
Problem:
write a java program to create a Movie class with properties such as title, director, year (object variables)
and totalMovies (class variable). Implement a parameterized constructor to initialize 2 objects. Include an
object method to display the movie details and a class method to get the total number of movies.

Prerequisites:
i. Basic knowledge of Java programming language.
ii. Familiarity with object-oriented programming concepts.
iii. Understanding of variables, methods, and constructors in Java.

Learning Outcomes:
i. Understanding the concept of class variables and their usage.
ii. Differentiating between class variables and object variables.
iii. Understanding the role of constructors in initializing object properties.
iv. Implementing object methods to perform specific actions.
v. Utilizing class methods to access shared data or perform operations that don't depend on object
state.

Problem Analysis:
The program aims to create a Movie class and demonstrate the usage of class variables, object variables,
constructors, class methods, and object methods. It sets the properties of movies using a parameterized
constructor and displays the movie details using an object method. Additionally, it calculates and displays
the total number of movies using a class method.

Background Theory:
 Class variables are shared among all instances of a class. They are declared with the ‘static’
keyword.
 Object variables have unique values for each instance.
 Constructors are special methods used to initialize object properties when an object is created. It
has the same name as the class name and it does not return anything. It can have parameters.
 Object methods perform actions specific to each object, whereas class methods are associated
with the class and can be called without creating an object.
 Class methods are accessed using the class name. They are declared with the ‘static’ keyword.
 Object methods are accessed using the object instance.
 The main method serves as the entry point of the program.
Algorithm Design:
1. Create a Movie class.
2. Declare class variables, such as totalMovies, to keep track of the number of movies.
3. Declare object variables, such as title, director, and year, to store the movie properties.
4. Implement a parameterized constructor to set the movie properties and increment totalMovies.
5. Define an object method, such as displayMovieDetails(), to display the movie properties.
6. Implement a class method, such as getTotalMovies(), to return the total number of movies.
7. In the main function, create movie objects using the constructor and set their properties.
8. Use object methods to display the movie details.
9. Use the class method to display the total number of movies.

Code:

Figure 1: Movie Class


Figure 2: Main Class

Figure 3: Output
Practice Problems
1. Create an Employee class with properties such as name, age, designation, salary (object variables)
and company name, company address (class variables). Implement a parameterized constructor
to initialize 3 objects. Include an object method to display the employee details and a class method
to display the total number of employees.

2. Create a Book class with properties such as title, author, year (object variables) and genre (class
variable). Implement a parameterized constructor to initialize 3 objects. Include an object method
to display the book details and a class method to display the total number of books.

3. Create a Student class with properties such as id, name, department, cgpa (object variables) and
university (class variable). Implement a parameterized constructor to initialize 3 objects. Include
an object method to display the student details and a class method to display the total number of
students.
LAB Sheet #3
OBJECTIVES:
i. To be familiar with Scanner class
ii. To learn how to take input from user for different data types
iii. To learn how to create objects after taking input from user

Problems:
1. Take an integer input from user and check whether the number is palindrome or
not.
2. Take a string input from user and reverse it
3. Solve Lab Sheet#2 using Scanner class (take the object variables as input from user)

Prerequisites:
i. Basic knowledge of Java programming language, including variables, data types, and
control structures.
ii. Understanding of basic input/output operations in Java.
iii. Familiarity with the concept of user input and how it can be read from the console.

Learning Outcomes:
i. Ability to take input from the user of various data types in Java.
ii. Understanding of the Scanner class and its methods for reading user input.
iii. Familiarity with type conversion and parsing techniques in Java.
Problem Analysis:
Taking input from the user of various data types in Java involves the following steps:

i. Create an instance of the Scanner class to read input from the user.
ii. Prompt the user for input by displaying a message or a question.
iii. Use the appropriate method of the Scanner class to read the input based on the desired
data type.
iv. Store the user's input in a variable of the corresponding data type.
v. Use the input data in your program as needed.
Background Theory:
Data Types: In Java, data types determine the kind of values that variables can hold. Common
data types include int (for integers), double (for floating-point numbers), char (for characters),
and String (for text).
Scanner Class: The Scanner class in Java provides methods to read input from various sources,
such as the console or files. It offers methods like nextInt(), nextDouble(), nextLine(), etc., to read
input of different data types.
Type Conversion: Java supports automatic type conversion for certain data types, such as
converting an int to a double. However, explicit type conversion is required in some cases,
especially when reading user input. This can be achieved using methods like Integer.parseInt(),
Double.parseDouble(), etc., to convert strings to the desired data type.

Example of integer input:

Figure 1: Taking integer input from user

Figure 2: Output
Example of String input:

Figure 3: Taking String input from user

Figure 4: Output

Solution for Problem 1:


Figure 5: Code to Check whether a number is palindrome or not

Figure 6: Output
Solution for problem 2:

Figure 7: Code to reverse String

Figure 8: Output

*******Solve Problem 3 on your Own*******


Practice Problems
1. Create a Book class with properties such as title, author, year (object variables) and genre (class
variable). Implement a parameterized constructor to initialize 3 objects (Get the object variables as
input from the user). Include an object method to display the book details and a class method to
display the total number of books.

2. Create a Student class with properties such as id, name, department, cgpa (object variables) and
university (class variable). Implement a parameterized constructor to initialize 3 objects (Get the
object variables as input from the user). Include an object method to display the student details and
a class method to display the total number of students.
LAB Sheet #4
OBJECTIVES:
i. To be familiar with one dimensional and two-dimensional array in java
ii. To be familiar with array of objects
iii. To be familiar with String class
iv. To be familiar with ArrayList and LinkedList
Problem 1:
Create a program to calculate the average of the numbers in an array.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of arrays and loops

Learning Outcome:
i. By implementing this program, you will learn how to iterate over an array and calculate
the sum of its elements.
Problem Analysis:
After declaring and initializing an array of integers, we need to calculate the sum of all the
numbers in the array.

Background Theory:
To calculate the sum of numbers in an array, we iterate over each element of the array and add
it to a running total.

Algorithm Design:
1. Initialize a variable sum to 0.
2. Iterate over each element num in the array.
3. Add num to the sum variable.
4. After iterating through all the elements, the sum variable will contain the total sum of the
numbers in the array.
5. Output the value of sum.

Code:
Figure 1: One Dimensional Array

Figure 2: Output

Problem 2:
Write a program to transpose a matrix.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of multidimensional arrays and loops

Learning Outcome:
i. By implementing this program, you will learn how to transpose a matrix, which involves
interchanging rows and columns.

Problem Analysis:
Given a matrix represented as a two-dimensional array, we need to transpose the matrix, i.e.,
convert its rows into columns and columns into rows.

Background Theory:
The transpose of a matrix is obtained by interchanging its rows with columns. In a matrix of size
M x N, the resulting transposed matrix will have dimensions N x M.

Algorithm Design:
i. Create a new matrix with dimensions N x M, where N is the number of columns in the
original matrix and M is the number of rows.
ii. Iterate over each row and column of the original matrix.
iii. Assign the value at the current row and column in the original matrix to the new matrix
at the current column and row.
iv. The resulting new matrix will be the transpose of the original matrix.

Code:
Figure 3: Two Dimensional Array
Figure 4: Two dimensional Array Output

Problem 3:
write a java program based on various String operations using String methods.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of string manipulation and methods

Learning Outcome:
i. By implementing this program, you will learn how to perform common string operations
such as concatenation, length calculation, substring extraction, case conversion, and
string comparison.

Problem Analysis:
The program will showcase different operations on strings, such as concatenating two strings,
calculating the length of a string, extracting a substring, converting case (uppercase/lowercase),
and comparing two strings.

Background Theory:
Strings are immutable sequences of characters in Java. Various methods are available to
manipulate strings, such as concatenation using the + operator or the concat() method, getting
the length with the length() method, extracting substrings using substring(), converting case
using toUpperCase() and toLowerCase(), and comparing strings with equals() and compareTo()
methods.
Algorithm Design:
1. Create two strings str1 and str2 with sample values.
2. Perform concatenation of str1 and str2 using the + operator and concat() method, and
store the result in a new string concatenated.
3. Calculate the length of str1 and store it in an integer variable length.
4. Extract a substring from str1 using the substring() method, starting from index 2, and
store it in a new string substring.
5. Convert str1 to uppercase using the toUpperCase() method and store it in a new string
uppercase.
6. Convert str2 to lowercase using the toLowerCase() method and store it in a new string
lowercase.
7. Compare str1 and str2 using the equals() method and store the result in a boolean
variable areEqual.
8. Compare str1 and str2 lexicographically using the compareTo() method and store the
result in an integer variable comparison.
9. Output the results of the operations.

Code:

Figure 5: Various String operations


Figure 6: String Output

Problem 4:
Create a Book class with properties such as title, author, year, genre. Implement a parameterized
constructor to initialize 3 objects. Store the objects in an array and then display them. Remove
a particular object and then display the existing objects.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of classes, objects, and arrays in Java

Learning Outcome:
i. By implementing this program, you will learn how to create a class, define properties,
implement a parameterized constructor, create objects, store objects in an array, and
perform operations on the array.

Problem Analysis:
We need to create a Book class with properties such as title, author, year, and genre. We will
implement a parameterized constructor to initialize the objects and include an object method to
display the book details. The program will store these objects in an array and demonstrate how
to remove an object from the array by assigning null to a particular index.

Background Theory:
In Java, classes are used to create objects with defined properties and behaviors. The
parameterized constructor is used to initialize the objects with provided values. Arrays are used
to store multiple objects of the same type. To remove an object from an array, we can assign null
to the particular index.

Algorithm Design:
1. Create a Book class with properties: title, author, year, and genre.
2. Implement a parameterized constructor in the Book class to initialize the objects.
3. Include an object method displayDetails() in the Book class to display the book details.
4. Create an array books of Book objects and initialize it with 3 objects using the
parameterized constructor.
5. Iterate over the books array and call the displayDetails() method for each object to display
their details.
6. Remove an object by assigning null to a particular index in the books array.
7. Iterate over the updated books array and call the displayDetails() method for each object
to display their details again.
Code:

Figure 7: Book Class


Figure 8: Main Class
Figure 9: Output
Problem 5:
write a program to create an arraylist and a linked list of integers. Apply various methods such as
add, size, get, set, remove and sort.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of ArrayList and LinkedList data structures
Learning Outcome:
i. Create and use ArrayList and LinkedList to store and manipulate integers or any other
object
ii. Implement various methods provided by these data structures, such as add, size, get, set,
remove, and sort.

Problem Analysis:
The program needs to create an ArrayList and a LinkedList of integers. It will then perform various
operations on these data structures, such as adding elements, getting the size, accessing
elements, modifying elements, removing elements, and sorting the elements.

Background Theory:
ArrayList and LinkedList are two commonly used data structures in Java. ArrayList is implemented
as a dynamic array, while LinkedList is implemented as a doubly-linked list. ArrayList provides fast
random access, while LinkedList provides efficient insertion and deletion operations.

Algorithm Design:
1. Create an ArrayList called arrayList of type Integer.
2. Create a LinkedList called linkedList of type Integer.
3. Add elements to the arrayList and linkedList using the add() method.
4. Get the size of arrayList and linkedList using the size() method.
5. Access elements at specific indices using the get() method.
6. Modify elements at specific indices using the set() method.
7. Remove elements at specific indices using the remove() method.
8. Sort the elements in arrayList and linkedList using the Collections.sort() method.
9. Print the contents of arrayList and linkedList using a loop.
Code:

Figure 10: List Operations


Figure 11: List Output

Practice Problems

1. Write a program to sort an array using bubble sort, selection sort and merge sort.
2. Write a program to multiply two matrices.
3. Solve problem 4 by using ArrayList, LinkedList and their various methods
4. Solve practice problems from Lab Sheet #3 using array, ArrayList and LinkedList.
LAB Sheet #5

OBJECTIVES:
i. To be familiar with different types of constructors
ii. To be familiar with the concept of overloading (Compile time polymorphism)
iii. To be familiar with the ‘this’ keyword

Problem:
Create a class called Car with properties such as make, model, year, color, price. Use the ‘this’
keyword, overload constructor and overload another method.

Prerequisites:
i. Basic knowledge of Java programming language.
ii. Understanding of classes and objects in Java.
iii. Knowledge of constructors and method overloading in Java.
iv. Familiarity with the ‘this’ keyword.
Learning outcomes:
i. Understanding how to use the ‘this’ keyword to refer to instance variables within a class.
ii. Understanding constructor overloading and its benefits in providing flexibility to create
objects with different sets of parameters.
iii. Understanding method overloading and its usefulness in creating multiple methods with
the same name but different parameter lists.

Title:
A Class Implementation for Car Properties and Methods with Constructor Overloading, Method
Overloading and the ‘This’ keyword

Objective:
The objective of this Java program is to demonstrate and to apply the concept of constructor
overloading and method overloading as well as to utilize the ‘this’ keyword by creating a Car
class with various properties, constructors and methods.

Introduction:
This report presents the implementation of a Car class in Java programming language. The Car
class will have properties such as make, model, year, color, and price. We will utilize the concepts
of constructor overloading and method overloading to create different constructors and
methods with varying parameter sets. Additionally, we will apply the ‘this’ keyword to refer to
the current instance within the class.
Problem Understanding:
The problem is to design a Car class that represents a car object. The Car class should have
properties such as make, model, year, color, and price. We need to implement overloaded
constructors and overloaded methods with different sets of parameters to instantiate and
manipulate car objects. Additionally, we require to utilize the ‘this’ keyword to refer to the
current instance within the class.

Background Theory:
Constructors:
In Java, a constructor is a special method that is used to initialize objects of a class. It has the
same name as the class and does not have a return type, not even void. Constructors are called
implicitly when an object is created using the new keyword. They are primarily used to set initial
values to the instance variables of an object.

Key Points about Constructors:

 Constructors are used to initialize the state of an object.


 Constructors have the same name as the class.
 Constructors do not have a return type.
 If a class does not have any explicitly defined constructors, a default constructor is
automatically provided by Java
The ’this’ Keyword:
The ‘this’ keyword is a reference to the current object within a class. It can be used to refer to
the instance variables or methods of the current object. The primary purposes of the ‘this’
keyword are:

 Distinguishing between instance variables and local variables or method parameters that
have the same name.
 Calling one constructor from another constructor within the same class.

Key Points about the ‘this’ Keyword:

 ‘this’ can be used to refer to instance variables within a class.


 ‘this’ can be used to invoke a constructor from another constructor within the same class.
 ‘this’ can be used to return the current object from a method.
Constructor Overloading:
Constructor overloading is the process of defining multiple constructors in a class, each with a
different parameter list. This allows us to create objects with different initializations based on
the provided arguments. By overloading constructors, we can provide flexibility in creating
objects with varying properties.

Method Overloading:
Method overloading is the ability to have multiple methods with the same name but different
parameter lists within a class. By overloading methods, we can perform similar operations on
different sets of arguments. Method overloading improves code readability and provides
convenience by allowing multiple ways to interact with an object.

Algorithm Design:
1. Define the Car class with private instance variables for make, model, year, color, and
price.
2. Implement overloaded constructors that accept different sets of parameters and use
the "this" keyword to assign values to the instance variables as well as call one
constructor from another
3. Implement overloaded methods that perform similar operations but on different
parameter sets.
4. Create objects of the Car class using different constructors.
5. Invoke the overloaded methods on the car objects with different arguments.
6. Display the results of the method invocations.

Code:
Figure 1: Car class
Figure 2: Main class

Figure 3: Output
Conclusion:
In this report, we successfully implemented a Car class in Java with properties such as make,
model, year, color, and price. We utilized constructor overloading to create different constructors
for the Car class, allowing us to initialize objects with varying parameter sets. Additionally, we
implemented method overloading to perform similar operations on different parameter sets. The
"this" keyword proved useful in distinguishing between instance variables and local variables or
parameters with the same name. The output demonstrated the creation of car objects using
constructors and the invocation of overloaded methods with different arguments. Overall, the
concepts of constructor and method overloading, along with the ‘this’ keyword, enhance the
flexibility and reusability of the Car class.

Practice Problems
1. Create a class called Person with properties such as name, age, gender, address. Use
constructor overloading, method overloading and the ‘this keyword’.
2. Create a class called Employee with properties such as name, id, salary, designation. Use
constructor overloading, method overloading and the ‘this keyword’.
LAB Sheet #6

OBJECTIVES:
i. To be familiar with encapsulation
ii. To be familiar with Get and Set methods

Problem:
Create a class called Car with properties such as make, model, year, color, price. Include getter
and setter methods for each property (Encapsulation).

Prerequisites:
i. Basic knowledge of Java programming language.
ii. Understanding of classes and objects in Java.
iii. Understanding of getter and setter methods.

Learning outcomes:
i. Understanding how to create a class with properties and encapsulate them using private
access modifiers.
ii. Understanding how to use getter and setter methods to access and modify the private
properties.
iii. Understanding the benefits of encapsulation in terms of data protection and code
maintainability.
iv. Gaining experience in creating and using getter and setter methods to interact with class
properties.

Title:
A Class Implementation for Car Properties and Methods with Encapsulation

Objective:
The objective of this Java program is to demonstrate and apply one of the primary concepts of
object-oriented programming, encapsulation, by creating a car class with various properties,
constructor and methods.

Introduction:
This report presents a class implementation in Java for a car object with encapsulation. The class
called "Car" will have properties such as make, model, year, color, and price. Additionally, getter
and setter methods will be provided for each property to ensure data encapsulation and
controlled access.

Problem Understanding:
The goal is to design a class that represents a car object with various private properties.
Encapsulation is essential to ensure that the properties are accessed and modified through
controlled methods, providing data integrity and security. We need to use getter and setter
methods for each property to enforce data validation and provide a consistent interface for
accessing and updating the car properties.

Background Theory:
In Java, access modifiers, encapsulation, and getter/setter methods are key concepts in object-
oriented programming that help achieve data hiding, encapsulation, and control over the
accessibility of class members. Let's explore each of these concepts:

a. Access Modifiers:
Access modifiers determine the accessibility of classes, variables, methods, and
constructors within Java. There are four types of access modifiers in Java:
ii. Public: The public access modifier allows unrestricted access to a class
member from any other class or package.
iii. Private: The private access modifier restricts access to the member
within the same class. It is the most restrictive modifier.
iv. Protected: The protected access modifier allows access within the
same class, derived/subclass, and package.
v. Default (no modifier): When no access modifier is specified, it is
referred to as the default access modifier. It allows access within the
same package only.
b. Encapsulation:
Encapsulation is a mechanism that combines data and methods (or behaviors) within a
class, hiding the internal details and providing controlled access to the class members. It
helps in achieving data abstraction and protecting the data from unauthorized access and
modifications.
To achieve encapsulation, one typically marks the class variables (fields) as private and provides
public getter and setter methods to access and modify the data. This ensures that the internal
state of the object is controlled and maintained consistently.
c. Getter and Setter Methods:
Getter and setter methods (also known as accessors and mutators) are public methods
used to retrieve (get) and modify (set) the values of private variables, respectively. They
provide controlled access to the class fields while encapsulating the implementation
details.

The naming convention for getter and setter methods is based on the field name, with "get" and
"set" prefixes, respectively. For example, if there is a private field called "name," the
corresponding getter and setter methods would be "getName()" and "setName(String name)".

Getter methods are used to access the value of a field, while setter methods are used to set or
modify the value of a field. These methods can include additional logic, such as validation or
calculations, before accessing or modifying the field.

By using getter and setter methods, one can enforce data validation rules, implement read-only
or write-only properties, and provide a level of abstraction to the internal representation of data.

Overall, access modifiers, encapsulation, and getter/setter methods in Java enable a programmer
to control the visibility and accessibility of class members, protect data integrity, and provide a
standardized way to access and modify private variables while encapsulating the implementation
details.

Algorithm Design:
1. Create a class called "Car" with the following properties:
i. Make
ii. Model
iii. Year
iv. Color
v. price
3. Implement getter and setter methods for each property:
i. For each property, create a getter method that returns the current
value of the property.
ii. For each property, create a setter method that takes a parameter and
assigns the new value to the property.
4. Instantiate a Car object and set its properties using the user input:
i. Create an instance of the Car class.
ii. Use the setter methods to set the values of the car properties based on
the user input.
5. Repeat step 3 for 2 more objects.
6. Display objects using getter methods.
Code:
The Car class encapsulates the properties of a car using private access modifiers. This ensures
that the properties cannot be accessed directly from outside the class, promoting encapsulation.
Each property has a corresponding private field: make, model, year, color, and price.

figure 1: Class Car

For each property, there are two methods: a getter method and a setter method.
The getter methods, such as getMake(), getModel(), getYear(), getColor(), and getPrice(), return
the values of the respective properties.
The setter methods, such as setMake(String make), setModel(String model), setYear(int year),
setColor(String color), and setPrice(double price), allow you to set the values of the respective
properties.

figure 2: Getter and Setter methods


Three Car objects (car1, car2, and car3) are created and their properties are set using the setter
methods inside the main method.

figure 3: Object creation using setter methods


The System.out.println statements are used to display the details of each car object, including
make, model, year, color, and price using the getter methods inside the main method.

figure 4: Object display using getter methods


The output of the program is shown below:

figure 5: Code output

Conclusion: In conclusion, we have successfully implemented a Java class named "Car" with
encapsulation. The class provides properties such as make, model, year, color, and price, along
with getter and setter methods for each property. The user's input is obtained through the
Scanner class, and the car object's properties are set accordingly. Encapsulation ensures that the
properties are accessed and modified using controlled methods, promoting data integrity and
security.

Practice Problems
1. Create a class called Person with properties such as name, age, gender, address. Include
getter and setter methods for each property.
2. Create a class called Employee with properties such as name, id, salary, designation.
Include methods to get and set the properties.
LAB Sheet #7
OBJECTIVES:
i. To be familiar with inheritance (super class and subclass)
ii. To be familiar with the ‘super’ keyword
iii. To be familiar with method overriding (run time polymorphism)
Problem:
create a class named ElectronicDevice with properties such as company, model, price, color.
Create two subclasses Television (with additional property screen size) and WashingMachine
(with additional property capacity). Create the main class to initialize objects of the subclasses,
store them in an ArrayList and display them. Use the ‘super’ keyword to call constructor of the
superclass from the subclasses and use the concept of method overriding.

Prerequisites:
i. Basic understanding of Java programming language
ii. Knowledge of object-oriented programming concepts, such as inheritance, encapsulation,
and polymorphism
Learning Outcomes:
i. Understanding how to create and use classes and subclasses in Java
ii. Implementing inheritance and method overriding
iii. Applying the ‘super’ keyword
Problem Analysis:
We need to create a Java class called "ElectronicDevice" with properties such as company, model,
price, and color. Then, we will create two subclasses, "Television" and "WashingMachine," which
inherit from the "ElectronicDevice" class. The "Television" class will have an additional property
called screen size, while the "WashingMachine" class will have an additional property called
capacity. We will also create a main class to initialize objects of the subclasses, store them in an
ArrayList, and display their information.

Background Theory:
Inheritance: Inheritance allows a subclass to inherit properties and methods from its superclass.
It promotes code reuse and provides a hierarchical structure to organize classes.
Super Keyword: The "super" keyword is used to refer to the superclass's members (properties or
methods or constructor) from a subclass. It is particularly useful when the superclass and subclass
have members with the same name, and we need to differentiate between them.
Method Overriding: Method overriding is the ability of a subclass to provide a different
implementation of a method that is already defined in its superclass. It allows us to define
specialized behavior in the subclass.
Algorithm Design:

1. Define the "ElectronicDevice" class:


i. Declare private properties: company, model, price, and color.
ii. Create a parameterized constructor to initialize the properties.
iii. Provide getters and setters for each property.
2. Define the "Television" class:
i. Inherit from the "ElectronicDevice" class using the "extends"
keyword.
ii. Declare a private property: screenSize.
iii. Create a parameterized constructor that includes the additional
property.
iv. Provide a getter and setter for the screenSize property.
v. Override the toString() method to display the information of the
Television object.
3. Define the "WashingMachine" class:
i. Inherit from the "ElectronicDevice" class using the "extends"
keyword.
ii. Declare a private property: capacity.
iii. Create a parameterized constructor that includes the additional
property.
iv. Provide a getter and setter for the capacity property.
v. Override the toString() method to display the information of the
WashingMachine object.
4. Define the "Main" class:
i. Create an ArrayList to store ElectronicDevice objects.
ii. Initialize Television and WashingMachine objects using the
parameterized constructors.
iii. Add the objects to the ArrayList.
iv. Iterate over the ArrayList and display the information of each
object using the toString() method.
Code:

Figure 1: Super Class


Figure 2: Sub Classes

Figure 3: Main Class


Figure 4: Output

Practice Problems

1. Create a class named "Vehicle" with properties such as "brand", "model", "price", and "color".
Create two subclasses, "Car" and "Motorcycle," with additional properties specific to each
class. Create a main class to initialize objects of the subclasses, store them in an ArrayList, and
display their information. Use the 'super' keyword to call the constructor of the superclass
from the subclasses and utilize method overriding.

2. Create a class named "Shape" with properties such as "name" and "color". Create two
subclasses, "Circle" and "Rectangle," with additional properties specific to each class.
Implement methods in the subclasses to calculate the area and perimeter of each shape.
Create objects of the subclasses, store them in an ArrayList, and display their information.

3. Create a class named "Employee" with properties such as "name," "id," and "salary." Create
two subclasses, "Manager" and "Engineer," with additional properties specific to each class.
Implement a method in each subclass to calculate the total salary by including additional
bonuses. Create objects of the subclasses, store them in an ArrayList, and display their
information.

4. Create a class named "Book" with properties such as "title," "author," and "price." Create two
subclasses, "FictionBook" and "NonFictionBook," with additional properties specific to each
class. Implement methods in the subclasses to display the book details and perform book-
specific actions. Create objects of the subclasses, store them in an ArrayList, and display their
information.
LAB Sheet #8
OBJECTIVES:
i. To be familiar with abstract methods and abstract classes
ii. To be familiar with interfaces and multiple inheritance

Problem 1:
Create a java abstract class "Booking" with properties such a scan represent different types of
bookings, such as flight bookings, hotel bookings, and event bookings. Subclasses have their own
speific properties and they can implement methods like confirmBooking() and cancelBooking()
based on the specific booking requirements. Implement main class to store different booking
objects in a single ArrayList.

Prerequisites:
I. Basic knowledge of Java programming language
II. Understanding of object-oriented programming concepts

Learning Outcome:
I. Understanding the concept and usage of abstract classes in Java
II. Implementing abstract methods in concrete subclasses
III. Storing and managing different types of bookings using polymorphism

Problem Analysis:
The problem is to represent different types of bookings using an abstract class and its subclasses.
Each booking type (flight, hotel, event) has its own specific attributes and behaviors.
The program should allow confirming and canceling bookings for each type.

Background Theory:
 Abstract classes in Java provide a way to define common attributes and behaviors for
related classes.
 Abstract classes cannot be instantiated but can be extended by concrete subclasses.
 Concrete subclasses must implement the abstract methods defined in the abstract class.

Algorithm Design:
1. Create an abstract class "Booking" with common attributes and abstract methods for
confirming and canceling bookings.
2. Create concrete subclasses (e.g., "FlightBooking," "HotelBooking," "EventBooking") that
extend the abstract class.
3. Implement the abstract methods in each concrete subclass based on the specific booking
requirements.
4. In the main class, create instances of different booking types and add them to an ArrayList
of type "Booking."
5. Iterate over the bookings in the ArrayList and call the confirmBooking() and
cancelBooking() methods for each booking.

Code:

Figure 1: Booking class


Figure 2: FlightBooking class

Figure 3: HotelBooking class


Figure 4: EventBooking class

Figure 5: Main class

Figure 6: Output
Problem 2:
Write a program to handle different types of shapes, such as circles, rectangles, and triangles.
Each shape type requires common attributes defined in an abstract class (e.g., color,
coordinates), interfaces for behavior (e.g., calculateArea()), and multiple inheritance to handle
shape-specific interfaces.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of object-oriented programming concepts, including abstract classes,
interfaces, and inheritance

Learning Outcome:
i. Understanding the concept of abstract classes and interfaces in Java
ii. Implementing abstract classes to define common attributes for shape types
iii. Implementing interfaces to provide behavior contracts for shape types
iv. Utilizing multiple inheritance to handle shape-specific interfaces

Problem Analysis:
The problem is to handle different types of shapes, such as circles, rectangles, and triangles, while
providing common attributes and behavior. Each shape type requires common attributes like
color and coordinates, behavior to calculate the area, and shape-specific behavior. The program
should allow creating and manipulating different shape objects while leveraging abstract classes,
interfaces, and multiple inheritance.

Background Theory:
 Abstract classes in Java provide a way to define common attributes and methods for
related classes.
 Interfaces define behavior contracts that can be implemented by classes.
 Multiple inheritance allows a class to inherit from multiple interfaces, enabling the
implementation of multiple behavior contracts.

Algorithm Design:
1. Create an abstract class "Shape" with common attributes (e.g., color, coordinates) and an
abstract method (e.g., calculateArea()) for calculating the area of a shape.
2. Create interfaces for shape-specific behaviors, such as "Resizable" for shapes that can be
resized.
3. Implement concrete classes for each shape type (e.g., Circle, Rectangle, Triangle) that
extend the "Shape" abstract class and implement shape-specific interfaces.
4. In the concrete shape classes, implement the abstract method "calculateArea()" based on
the specific shape's formula.
5. Implement the shape-specific behavior in the concrete classes by implementing the
interfaces' methods.
6. In the main class, create instances of different shape types and demonstrate their
behavior (e.g., calculate area, resize).
Code:

Figure 7: Abstract class and interface


Figure 8: Subclasses
Figure 9: Main class

Figure 10: Output class


Practice Problems

1. Write a program to represent different types of products, such as electronics, clothing, and
books. Each product type requires common attributes defined in an abstract class (e.g., name,
price), type-specific properties, interfaces for behavior (e.g., calculateDiscount()), and
multiple inheritance to handle product-specific interfaces.

2. Write a program to manage different types of vehicles, such as cars, motorcycles, and trucks.
Each vehicle type requires common attributes defined in an abstract class (e.g., model, year),
type-specific properties, interfaces for behavior (e.g., startEngine()), and multiple inheritance
to handle vehicle-specific interfaces.

3. Write a program to manage different types of bank accounts, such as savings, checking, and
credit. Each account type requires common attributes defined in an abstract class (e.g.,
accountNumber, balance), type-specific properties, interfaces for behavior (e.g., deposit(),
withdraw()), and multiple inheritance to handle account-specific interfaces.

4. Write a program to handle different types of users, such as regular users, business accounts,
and influencers. Each user type requires common attributes defined in an abstract class (e.g.,
username, profile picture), type-specific properties, interfaces for behavior (e.g.,
postContent()), and multiple inheritance to handle user-specific interfaces.

5. Write a program to handle different types of employees, such as full-time, part-time, and
contractors. Each employee type requires common attributes defined in an abstract class
(e.g., name, employeeId), type-specific properties, interfaces for behavior (e.g.,
calculateSalary()), and multiple inheritance to handle employee-specific interfaces.

6. Write a program to manage different types of students, such as undergraduate, graduate, and
doctoral students. Each student type requires common attributes defined in an abstract class
(e.g., name, studentId), type-specific properties, interfaces for behavior (e.g., enrollCourse()),
and multiple inheritance to handle student-specific interfaces.
LAB Sheet #9
OBJECTIVES:
iii. To be familiar with different types of exception handling
iv. To be familiar with reading from and writing to file
Problem 1:
Write a Java program to illustrate different types of exceptions (runtime and compile time). Use
try, catch, throw, throws and finally.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of exception handling concepts
iii. Familiarity with try-catch blocks, throw, throws, and finally statements

Learning Outcomes:
i. Understand the different types of exceptions in Java
ii. Learn how to handle exceptions using try-catch blocks
iii. Implement throwing and catching custom exceptions
iv. Gain experience in using the finally block for cleanup operations

Problem Analysis:
We will create a Java program that demonstrates different types of exceptions, both runtime and
compile time. The program will use try-catch blocks to handle exceptions, throw custom
exceptions, use the throws keyword to declare exceptions, and utilize the finally block for cleanup
operations.

Background Theory:
In Java, exceptions are categorized into two types: runtime exceptions (unchecked exceptions)
and compile-time exceptions (checked exceptions). Runtime exceptions are not checked at
compile time, while compile-time exceptions are checked at compile time and must be declared
or handled using try-catch blocks.

Algorithm Design:
1. Create a class named "ExceptionDemo" with a main method.
2. Inside the main method, define a variable "x" and assign it a value of 10.
3. Define another variable "y" and assign it a value of 0.
4. Use try-catch blocks to handle exceptions and perform the following operations:
a) Divide "x" by "y" and catch the ArithmeticException.
b) Access an array element beyond its bounds and catch the
ArrayIndexOutOfBoundsException.
c) Parse a non-integer string and catch the NumberFormatException.
d) Throw a custom exception named "CustomException" and catch it.
5. Implement the "CustomException" class by extending the Exception class.
6. Declare the "CustomException" using the throws keyword in the main method.
7. Use the finally block to print a message indicating the end of the program.
Code:

Figure 1: Different types of Exception

Figure 2: Output
Problem 2:
Write a Java program to Read line by line from a file. Each line contains name of a student and 3
integer numbers. Write the name of the student and the average of the 3 numbers to a file. Use
various exception handling techniques.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Familiarity with file handling in Java
iii. Understanding of exception handling concepts
iv. Familiarity with BufferedReader and BufferedWriter classes
Learning Outcome:
i. Understand how to read from and write to a file using BufferedReader and BufferedWriter
ii. Learn different exception handling techniques in file handling operations
iii. Gain experience in handling FileNotFoundException, IOException, and
NumberFormatException
iv. Apply additional input validation techniques to ensure non-negative numbers
Problem Analysis:
We need to read a file line by line, where each line contains the name of a student and three
integer numbers. We need to ensure that the numbers are non-negative. We will calculate the
average of the three non-negative numbers and write the name of the student along with the
average to another file. We will handle potential exceptions such as FileNotFoundException,
IOException, and NumberFormatException to ensure proper error handling. Additionally, we will
implement input validation to check for non-negative numbers.

Background Theory:
In Java, the BufferedReader class is used for efficient reading of characters from a file, and the
BufferedWriter class is used for efficient writing of characters to a file. These classes provide
methods for reading and writing lines of text. We can also perform additional input validation
to ensure that the numbers are non-negative.

Algorithm Design:
1. Create a text file named "input.txt" with the student's name and three integer numbers
on each line, separated by spaces.
2. Create a class named "StudentAverage" with a main method.
3. Inside the main method, declare and initialize a BufferedReader object named "reader"
with the FileReader object, passing the "input.txt" file path as an argument.
4. Declare and initialize a BufferedWriter object named "writer" with the FileWriter object,
passing the "output.txt" file path as an argument.
5. Use a try-catch block to handle the IOException that may occur during file reading and
writing operations.
6. Inside the try block, declare a String variable named "line" to store each line read from
the file.
7. Use a while loop to read each line from the file using the reader.readLine() method.
Terminate the loop when null is returned.
8. Inside the loop, split the line into an array of strings using the split() method, specifying a
space (" ") as the delimiter.
9. Extract the student's name from the array at index 0.
10. Convert the three numbers from strings to integers using the Integer.parseInt() method.
11. Check if any of the numbers are negative. If so, throw a custom exception named
"NegativeNumberException" with an appropriate error message.
12. Calculate the average of the three non-negative numbers.
13. Write the student's name and the average to the "output.txt" file using the writer.write()
method.
14. After the loop ends, close both the reader and writer using the close() method.
15. Handle the FileNotFoundException, IOException, NumberFormatException, and
NegativeNumberException using separate catch blocks.
16. Print appropriate error messages or stack traces in the catch blocks.

Code:
Figure 3: File Read Write

Figure 4: Input File


Figure 5: Output File

Practice Problems

1. Read a file containing names of employees and their salaries from the last 3 workplaces.
Calculate the average salary for each employee and write their name and average to a file.
Handle FileNotFoundException, IOException, NumberFormatException, and
NegativeNumberException.

2. Read a file line by line where each line has information about a football match (i.e. France 3
Italy 2). Write down the result of each match to another file (Winner and the number of goals
scored by them). If number of goals are equal for both teams, write “Match Drawn”. Handle
FileNotFoundException, IOException, NumberFormatException, and
NegativeNumberException.

3. Read a file containing names of cities and their populations. Determine the city with the
maximum population and write the information (city name, population). Handle
FileNotFoundException, IOException, NumberFormatException, and
NegativeNumberException.
LAB Sheet #10
OBJECTIVES:
i. Getting acquainted with Java Swing
ii. Creating a registration form using various Swing controls

Problem:

Create a registration form using GUI. Use controls such as label, textfield, radiobutton, checkbox, list,
combobox, and passwordfield.

Prerequisites:

i. Basic knowledge of Java programming language.


ii. Familiarity with object-oriented programming concepts.
iii. Understanding of event-driven programming.
iv. Familiarity with GUI components and their properties.

Learning Outcomes:

i. Understanding how to create a GUI registration form using Java.


ii. Learning how to use various GUI components such as labels, text fields, radio buttons,
checkboxes, lists, combo boxes, and password fields.
iii. Gaining experience in handling user input and events in a GUI application.
iv. Enhancing knowledge of event-driven programming and event handling.
v. Practicing designing and implementing user-friendly forms using appropriate GUI controls.
vi. Gaining proficiency in creating interactive Java applications with graphical interfaces.

Problem Analysis:

The task is to create a registration form using Java GUI, incorporating various controls such as labels,
text fields, radio buttons, checkboxes, lists, comboboxes, and password fields. The registration form
should allow users to enter their personal information and submit it.

Background Theory:

Java GUI (Graphical User Interface) allows us to create interactive applications with visual elements. It
provides a set of controls and components that can be used to design user-friendly interfaces. The Swing
framework in Java provides classes and methods for creating GUI applications.

The controls mentioned in the problem statement have specific purposes:

Label: Displays a text description or caption for other components.

TextField: Allows users to enter text.

RadioButton: Presents a set of mutually exclusive options, allowing users to select only one option.
Checkbox: Represents a choice that can be checked or unchecked.

List: Displays a list of selectable items.

ComboBox: A drop-down list that allows users to select an item from multiple options.

PasswordField: Like a text field, but the input is masked to hide the entered text (typically used for
password entry).

Algorithm Design:

1. Create a new Java project and set up the required libraries (e.g., Swing).
2. Create a new class for the registration form.
3. Initialize the necessary components (labels, text fields, radio buttons, checkboxes, list,
combobox, password field, and date chooser) within the class constructor.
4. Set the layout manager for the form (e.g., BorderLayout, GridBagLayout) to arrange the
components.
5. Add the components to the form using appropriate layout constraints.
6. Implement event handlers if required (e.g., button click to submit the form).
7. Run the application to display the registration form.
Code:

package registrationform;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RegistrationForm extends JFrame {


// Components
private JLabel nameLabel, emailLabel, genderLabel, countryLabel, passwordLabel,
confirmPasswordLabel, dobLabel;
private JTextField nameTextField, emailTextField;
private JRadioButton maleRadioButton, femaleRadioButton;
private JCheckBox javaCheckBox, pythonCheckBox;
private JList<String> countryList;
private JComboBox<String> occupationComboBox;
private JPasswordField passwordField, confirmPasswordField;
private JButton submitButton;
public RegistrationForm() {
setTitle("Registration Form");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initialize components
nameLabel = new JLabel("Name:");
nameTextField = new JTextField();
emailLabel = new JLabel("Email:");
emailTextField = new JTextField();
genderLabel = new JLabel("Gender:");
maleRadioButton = new JRadioButton("Male");
femaleRadioButton = new JRadioButton("Female");
countryLabel = new JLabel("Country:");
String[] countries = {"USA", "Canada", "UK", "India", "Australia"};
countryList = new JList<>(countries);
passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField();
confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordField = new JPasswordField();
submitButton = new JButton("Submit");
// Set layout manager
setLayout(new GridLayout(10, 2));
// Add components to the form
add(nameLabel);
add(nameTextField);
add(emailLabel);
add(emailTextField);
add(genderLabel);
ButtonGroup genderButtonGroup = new ButtonGroup();
genderButtonGroup.add(maleRadioButton);
genderButtonGroup.add(femaleRadioButton);
JPanel genderPanel = new JPanel();
genderPanel.add(maleRadioButton);
genderPanel.add(femaleRadioButton);
add(genderPanel);
add(countryLabel);
add(new JScrollPane(countryList));
add(passwordLabel);
add(passwordField);
add(confirmPasswordLabel);
add(confirmPasswordField);
add(submitButton);
// Event handler for submit button
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Perform registration form submission logic here
String name = nameTextField.getText();
String email = emailTextField.getText();
String gender = maleRadioButton.isSelected() ? "Male" : "Female";
String country = countryList.getSelectedValue();
String password = new String(passwordField.getPassword());
String confirmPassword = new String(confirmPasswordField.getPassword());
// Validate and process the registration data
// Display success or error message
JOptionPane.showMessageDialog(RegistrationForm.this, "Registration Successful!");
}
});
}
public static void main(String[] args) {
RegistrationForm registrationForm = new RegistrationForm();
registrationForm.setVisible(true);
}
}

Output:

Figure: Output

Sample Practice Problems:

1. Enhance the registration form by adding input validation to check if all required fields are filled
before submission.
2. Implement functionality to save the registered user's data to a file/database.
3. Add additional fields to the registration form, such as address, phone number, and a file chooser
for profile picture upload.
4. Implement a "Reset" button to clear all the form fields.
LAB Sheet #11
OBJECTIVES:
Create a real-world application with GUI using all OOP properties.

Problem:
Create an abstract class named "Vehicle" with properties such as "brand", "model", "price", and
"color". Create two subclasses, "Car" and "Motorcycle," with additional properties specific to
each class. The abstract class should have abstract methods to be implemented in the subclasses
based on specific vehicle-type. Initialize objects of the subclasses from GUI frames using tabbed
panes, store them in an ArrayList, and display their information in tables (inside GUI frames). Add
buttons for adding and removing vehicles and also a reset button to clear the fields in the GUI.

Prerequisites:
i. Basic knowledge of Java programming language
ii. Understanding of object-oriented programming concepts, including abstract classes,
inheritance, and interfaces
iii. Familiarity with GUI programming using Java Swing
Learning Outcomes:
i. Understanding the concept of abstract classes and their usage in Java
ii. Implementing abstract methods in subclasses based on specific vehicle types
iii. Creating subclasses with additional properties specific to each vehicle type
iv. Implementing graphical user interfaces (GUI) using Java Swing components
v. Handling user input and displaying data using GUI frames and tables
vi. Storing objects in an ArrayList for efficient data management
vii. Adding functionality to buttons for adding, removing, and resetting data in the GUI

Problem Analysis:
The problem is to create a program that manages vehicles, including cars and motorcycles, using
abstract classes and subclasses. The abstract class "Vehicle" will define common properties such
as brand, model, price, and color. The subclasses "Car" and "Motorcycle" will inherit from the
"Vehicle" class and have additional properties specific to each type. The abstract class will include
abstract methods that need to be implemented in the subclasses to cater to the specific behavior
of each vehicle type. The program will utilize GUI frames with tabbed panes for creating objects
of car and motorcycle, storing them in an ArrayList, and displaying their information in tables. The
GUI will have buttons for adding and removing vehicles, as well as a reset button to clear the input
fields.
Background Theory:
 An abstract class in Java is a class that cannot be instantiated and is used as a base for
subclasses.
 Abstract methods are declared in an abstract class without an implementation and must
be implemented in the subclasses.
 Inheritance allows subclasses to inherit properties and methods from the superclass.
 GUI programming with Java Swing involves using components like JFrame, JTabbedPane,
JTable, etc., to create interactive graphical interfaces.

Algorithm Design:
1. Create an abstract class "Vehicle" with properties such as brand, model, price, and color.
a. Include abstract methods to be implemented in the subclasses
based on the vehicle type.
2. Create subclasses "Car" and "Motorcycle" that inherit from the "Vehicle" class.
a. Add additional properties specific to each vehicle type.
b. Implement the abstract methods defined in the "Vehicle" class.
3. Create a GUI frame with tabbed panes for creating car and motorcycle objects.
a. Use text fields and buttons to collect user input.
b. Upon button click, create objects of the appropriate subclass and
store them in an ArrayList.
4. Create a table within the GUI frame to display the vehicle information.
a. Use a table model to manage the data.
b. Populate the table with the information of the created objects.
5. Add buttons for adding and removing vehicles.
a. Implement button actions to add and remove vehicles from the
ArrayList and update the table accordingly.
6. Add a reset button to clear the input fields.
a. Implement the button action to reset the input fields to their
initial state.
Code:
******Write the code on your own*****
Practice Problems
1. Create a program to manage a library system. Use an abstract class named "Item" to represent
different types of library items such as books, DVDs, and CDs. Each item should have
properties like title, author/artist, price, and genre. Implement subclasses for each item type
with additional properties specific to that type. Use a GUI with tabbed panes to add, remove,
and display items in a table.

2. Develop a student management system using Java. Use an abstract class named "Person" to
represent different types of persons such as students and teachers. Each person should have
properties like name, age, address, and contact information. Implement subclasses for
students and teachers with additional properties specific to each. Use a GUI with tabbed
panes to add, remove, and display student and teacher information in tables.

3. Create a payroll management system for a company. Use an abstract class named "Employee"
to represent different types of employees such as full-time employees and part-time
employees. Each employee should have properties like name, employee ID, hourly rate/salary,
and department. Implement subclasses for full-time and part-time employees with additional
properties specific to each. Use a GUI with tabbed panes to add, remove, and display
employee information in tables.

4. Develop a banking system that handles different types of accounts such as savings accounts,
current accounts, and fixed deposit accounts. Use an abstract class named "Account" to
represent common attributes like account number, account holder, and balance. Implement
subclasses for each account type with additional properties specific to that type. Use a GUI
with tabbed panes to perform account-related operations like deposit, withdrawal, and
display account details.

5. Create a ticket booking system for a cinema. Use an abstract class named "Ticket" to represent
different types of tickets such as movie tickets, concert tickets, and sports event tickets. Each
ticket should have properties like ticket ID, event name, date, and price. Implement subclasses
for each ticket type with additional properties specific to that type. Use a GUI with tabbed
panes to book tickets, cancel bookings, and display booked tickets.

6. Develop an inventory management system for a retail store. Use an abstract class named
"Product" to represent different types of products such as electronics, clothing, and groceries.
Each product should have properties like product code, name, price, and quantity. Implement
subclasses for each product type with additional properties specific to that type. Use a GUI
with tabbed panes to add products, update quantities, and display product details.

7. Create a restaurant management system that handles different types of dishes such as
appetizers, main courses, and desserts. Use an abstract class named "Dish" to represent
common attributes like dish name, ingredients, and price. Implement subclasses for each dish
type with additional properties specific to that type. Use a GUI with tabbed panes to add
dishes, remove dishes, and display the menu.
LAB Sheet #12

Open Ended Lab Final Exam

You might also like