Object Oriented Programming SEOO 122 Lab Manual
Object Oriented Programming SEOO 122 Lab Manual
Preface
Object-oriented programming is a powerful paradigm that promotes modularity, reusability,
and maintainability of code. Java, as one of the most popular programming languages, has been
widely adopted in both academia and industry for its robust support of OOP concepts. This lab
manual is divided into a series of practical exercises, each designed to build your proficiency
in Java's object-oriented features step by step. You will start with the basics, gradually
progressing to more advanced topics. Each lab includes clear objectives, technical
explanations, and hands-on tasks with sample code to reinforce your understanding. Key topics
covered in this lab manual are:
Classes and Objects: Learn how to define classes and create objects, the building blocks of
Java's OOP model.
Inheritance: Explore the concept of inheritance, enabling you to create new classes based on
existing ones.
Encapsulation: Understand the importance of data hiding and encapsulation for secure and
maintainable code.
Abstraction: Learn to create abstract classes and interfaces to define blueprints for your
classes.
Tools/ Technologies
• Java
• Eclipse
2
BS (Software Engineering) 2023
TABLE OF CONTENTS
Preface ....................................................................................................................................... 2
Tools/ Technologies .................................................................................................................. 2
LAB 1: Introduction to Eclipse, Java programs, Basic programming structure of Java . 4
LAB 2: Methods, Method signatures, Parameters and Arguments .................................... 6
LAB 3: Classes and Objects, Properties, and Behaviour ..................................................... 9
LAB 4: Constructors of classes and their utility, Constructor Overloading .................... 13
LAB 5: Static Variables and Static Methods, Basic concept of Final Keyword .............. 17
LAB 6: Encapsulation and its implementation, Access modifiers, Data Hiding .............. 20
LAB 7: Basic concept of inheritance, Parent and Child Classes ....................................... 23
LAB 8: Polymorphism through Method Overriding, Use of Protected keyword ............ 26
LAB 9: Use of Final Keyword in inheritance, Final classes, Final methods..................... 29
LAB 10: Object Casting and Dynamic Method Dispatch .................................................. 31
LAB 11: Abstract Classes and Abstract Methods .............................................................. 31
LAB 12: Interfaces in Java, Implementing interfaces ........................................................ 36
LAB 13: Exception Handling Fundamentals, Types of Exceptions .................................. 39
LAB 14: Graphical User Interface Components, Introduction to AWT, AWT classes .. 43
3
BS (Software Engineering) 2023
Objectives
In this lab, you will become familiar with the Eclipse Integrated Development Environment
(IDE), write your first Java program, and understand the basic structure of a Java program.
Theoretical Description
Java is a versatile and widely used programming language known for its portability and
powerful features. Eclipse is a popular IDE that simplifies Java development by providing a
user-friendly environment.
Lab Task
Task 1: Setting Up Eclipse
• Launch Eclipse IDE on your computer.
• Configure your workspace and create a new Java project.
• Familiarize yourself with the Eclipse interface, including the Package Explorer,
Editor, and Console.
4
BS (Software Engineering) 2023
Code Help:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
5
BS (Software Engineering) 2023
Theoretical Description
Methods are essential building blocks of Java programs. They encapsulate reusable blocks of
code and allow you to perform specific tasks. A method signature defines a method's name,
return type, and parameters.
Lab Task
Task 1: Creating a Simple Method
• Create a new Java class called "Calculator."
• Define a method named add within the class. This method should accept two integer
parameters and return their sum.
• Call the add method from the main method and display the result.
6
BS (Software Engineering) 2023
Code Help:
// Task 1: Simple Method
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
7
BS (Software Engineering) 2023
8
BS (Software Engineering) 2023
Theoretical Description
Classes and Objects: In Java, a class is a blueprint for creating objects. A class defines the
structure and characteristics (properties and behaviors) that its objects will have. Objects are
instances of classes, and they represent real-world entities or concepts.
Properties (Attributes): Properties are variables defined within a class that represent the state
or characteristics of objects. These properties are also referred to as attributes or fields. In this
lab, you will create a "Person" class with two properties: name and age. These properties
encapsulate information about a person.
Lab Task
Task 1: Creating a Class
• Create a new Java class named "Person."
• Define two properties within the "Person" class: name (a string) and age (an integer).
• Create a constructor that allows you to initialize these properties when an object is
created.
9
BS (Software Engineering) 2023
• In the main method of another class, create two objects of the "Person" class.
• Initialize their name and age properties using the constructor.
• Print out the details of these two persons.
Code Help:
// Task 1: Creating a Class
this.name = name;
this.age = age;
10
BS (Software Engineering) 2023
age++;
return name;
this.name = name;
return age;
this.age = age;
person1.introduce();
person2.introduce();
11
BS (Software Engineering) 2023
person1.birthday();
12
BS (Software Engineering) 2023
Theoretical Description
Constructors: Constructors are special methods in a Java class that are used to initialize the
object's state when it is created. They have the same name as the class and do not have a return
type. Constructors can be used to set default values for object properties, perform necessary
setup tasks, or accept initial values as parameters.
Default Constructor: If a class does not define any constructors, Java provides a default
constructor with no parameters. This default constructor initializes object properties to their
default values.
Lab Task
Task 1: Default Constructor
Create a new Java class named "Product."
public class Product {
// Properties
13
BS (Software Engineering) 2023
// Default Constructor
public Product() {
productName = "Unknown";
price = 0.0;
quantity = 0;
productName = name;
price = initialPrice;
quantity = initialQuantity;
productName = name;
price = 0.0;
quantity = 0;
14
BS (Software Engineering) 2023
Task 6: Testing
In the main method, create several instances of the "Product" class using various
constructors. Display their information to verify that the constructors are working as
expected.
public class Main {
15
BS (Software Engineering) 2023
defaultProduct.displayProductInfo();
customProduct.displayProductInfo();
namedProduct.displayProductInfo();
16
BS (Software Engineering) 2023
Theoretical Description
Static Variables: Static variables, also known as class variables, are shared among all
instances of a class. They are declared using the "static" keyword and are associated with the
class itself rather than with individual objects. Static variables are often used to store data that
is common to all objects of a class.
Static Methods: Static methods, also known as class methods, belong to the class rather than
to a specific instance of the class. They are also declared using the "static" keyword. Static
methods can be called using the class name and are often used for utility functions that do not
require access to object-specific data.
Final Keyword: The "final" keyword is used to declare constants, indicate that a method
cannot be overridden, or specify that a class cannot be extended (for methods and classes we
will use them later). When applied to variables, "final" indicates that the variable's value cannot
be changed once assigned.
Lab Task
Create a Java class named "Counter" that contains a static integer variable named "count."
Initialize "count" to 0.
// Static Variable
17
BS (Software Engineering) 2023
In the "Counter" class, create a static method named "incrementCount" that increments the
"count" variable by 1 each time it is called.
// Static Method
count++;
Create a Java class named "Circle" that represents a circle. Define a "final" double variable
named "PI" with a value of 3.14159 to represent the mathematical constant π (pi).
// Final Variable
In the main method of another class, create instances of the "Counter" class and test the static
variable and static method.
Counter.incrementCount();
Counter.incrementCount();
18
BS (Software Engineering) 2023
In the main method, create an instance of the "Circle" class and use the "PI" constant to
calculate the area of a circle.
19
BS (Software Engineering) 2023
Theoretical Description
Encapsulation: Encapsulation is one of the fundamental concepts of object-oriented
programming. It refers to the bundling of data (attributes) and methods (functions) that operate
on that data into a single unit called a class. Encapsulation helps in controlling access to the
internal state of an object, providing data security, and maintaining code modularity.
Access Modifiers: Access modifiers are keywords in Java that determine the visibility or
accessibility of classes, variables, methods, and constructors within and outside a class.
Common access modifiers include "public," "private," "protected," and "default." They control
how the members of a class can be accessed by other classes.
Data Hiding: Data hiding is a key aspect of encapsulation. It involves marking certain
members of a class as private to prevent direct access from outside the class. Instead, access to
these members is provided through public methods, ensuring controlled and safe interaction
with the object's internal state.
Lab Task
Task 1: Encapsulation
Create a Java class named "Student" that encapsulates student information. Include private
data members (e.g., name, roll number, and GPA) and public methods for setting and
retrieving these values.
20
BS (Software Engineering) 2023
this.name = name;
return name;
student1.setName("Alice");
student1.setRollNumber(101);
student1.setGPA(3.8);
21
BS (Software Engineering) 2023
22
BS (Software Engineering) 2023
Theoretical Description
Inheritance: Inheritance is a core concept in object-oriented programming that allows a new
class to inherit properties and behaviors (attributes and methods) from an existing class. The
existing class is referred to as the "parent" or "base" class, and the new class is known as the
"child" or "derived" class. Inheritance promotes code reuse and establishes a hierarchical
relationship among classes.
Parent and Child Classes: In Java, a parent class serves as a blueprint for one or more child
classes. Child classes inherit the attributes and methods of the parent class. They can also have
additional attributes and methods specific to their own functionality. In this lab, we will create
a simple parent class and a child class to understand how inheritance works.
Lab Task
// Attributes
// Constructor
this.make = make;
this.model = model;
23
BS (Software Engineering) 2023
// Additional attributes
// Constructor
this.year = year;
this.fuelType = fuelType;
24
BS (Software Engineering) 2023
Task 3: Demonstration
In the main method of another class, create instances of the "Car" class, set values for car-
specific attributes, and demonstrate the use of inherited attributes and methods.
myCar.displayCarInfo();
25
BS (Software Engineering) 2023
Theoretical Description
Method Overriding: Method overriding is a feature of object-oriented programming that
allows a child class to provide its own implementation for a method that is already defined in
its parent class. This enables customization of behavior in derived classes while maintaining
the same method signature.
Protected Keyword: In Java, the protected keyword is used to declare class members (fields
and methods) that are accessible within the same package and by subclasses (even if they are
in different packages). It provides a level of access control that restricts direct access from
outside the class or package.
Lab Task
26
BS (Software Engineering) 2023
Create a Java class named "Circle" as a child class of "Shape." Override the calculateArea
method in the "Circle" class to calculate the area of a circle using the formula: π * r^2, where
"r" is the radius.
// Additional attribute
// Constructor
this.radius = radius;
@Override
Task 3: Demonstration
In the main method of another class, create instances of the "Circle" class, set values for the
radius, and demonstrate the use of method overriding to calculate the area of circles.
27
BS (Software Engineering) 2023
28
BS (Software Engineering) 2023
Theoretical Description
Final Keyword: In Java, the final keyword is used to indicate that a class, method, or variable
cannot be extended, overridden, or modified, respectively.
• Final Class: A final class is a class that cannot be extended. It provides a way to prevent
the creation of subclasses, ensuring that the class's implementation remains unchanged.
• Final Method: A final method is a method that cannot be overridden by subclasses. It
preserves the specific behavior of a method in the parent class, preventing further
modification.
Lab Task
Task 1: Create a Final Class
Create a Java class named "FinalClass" and declare it as a final class. This class should have
a simple method.
// FinalClass.java
// A simple method
29
BS (Software Engineering) 2023
// SubClass.java
// ParentClass.java
// A final method
// ChildClass.java
30
BS (Software Engineering) 2023
Theoretical Description
Object Casting: Object casting is the process of converting a reference of one class to another
class. It is essential when you have a reference to a superclass object, but you need to access
the specific methods or properties of a subclass.
Lab Task
Task 1: Create Parent and Child Classes
Create a Java class named "Parent" with a method named display. Create another class named
"Child" that extends "Parent" and overrides the display method to provide different
functionality.
// Parent.java
// Child.java
@Override
31
BS (Software Engineering) 2023
// Main.java
32
BS (Software Engineering) 2023
Theoretical Description
Abstract Classes: An abstract class in Java is a class that cannot be instantiated on its own. It
serves as a blueprint for other classes and can contain both abstract and concrete methods.
Abstract classes are declared using the abstract keyword.
Abstract Methods: An abstract method is a method declared in an abstract class but does not
have a method body. Subclasses of an abstract class must provide implementations for all
abstract methods. Abstract methods are declared using the abstract keyword and followed by a
semicolon.
Lab Task
// Shape.java
Create two subclasses of "Shape" named "Circle" and "Rectangle." Implement the
calculateArea() method in both subclasses to calculate the area of a circle and a rectangle,
respectively.
33
BS (Software Engineering) 2023
// Circle.java
this.radius = radius;
@Override
// Rectangle.java
this.length = length;
this.width = width;
@Override
34
BS (Software Engineering) 2023
In the main Java class, create instances of "Circle" and "Rectangle" objects, call their
calculateArea() methods, and display the calculated areas.
// Main.java
35
BS (Software Engineering) 2023
Theoretical Description
Interfaces: In Java, an interface is a collection of abstract methods and constant variables
(variables with the final modifier). An interface defines a contract that classes implementing it
must adhere to by providing concrete implementations for all of its methods. Classes can
implement multiple interfaces.
Defining an Interface: An interface is defined using the interface keyword. It contains
method signatures and variable declarations, but the methods have no method bodies.
Implementing Interfaces: Classes implement interfaces using the implements keyword. They
must provide concrete implementations for all methods declared in the interface.
Variables in Interfaces: Interfaces can declare variables, which are implicitly public, static,
and final. These variables can be used to define constants that implementing classes can access.
Lab Task
Task 1: Define an Interface
Create an interface named "GeometricShape" with the following method signatures:
double calculateArea();
double calculatePerimeter();
java
Copy code
// GeometricShape.java
double calculateArea();
double calculatePerimeter();
36
BS (Software Engineering) 2023
Create a class named "Circle" that implements the "GeometricShape" interface. Implement
the calculateArea() and calculatePerimeter() methods for a circle.
// Circle.java
this.radius = radius;
@Override
@Override
// GeometricShape.java
double PI = 3.14159265359;
double calculateArea();
double calculatePerimeter();
37
BS (Software Engineering) 2023
// Main.java
38
BS (Software Engineering) 2023
Theoretical Description
Exception Handling Fundamentals: Exception handling is a mechanism in Java to deal with
runtime errors or exceptional conditions that may occur during program execution. Java
provides a robust framework for handling exceptions, which helps prevent program crashes
and allows graceful error recovery.
Types of Exceptions: Exceptions in Java can be categorized into two main types: checked
exceptions and unchecked exceptions (runtime exceptions). Checked exceptions must be
explicitly caught or declared, while unchecked exceptions can be caught, but it's not mandatory.
Using Exception Clauses:
• try: The try block is used to enclose the code that might throw an exception.
• catch: The catch block is used to catch and handle exceptions that occur within the try
block.
• throw: The throw statement is used to explicitly throw an exception.
• throws: The throws clause is used in method declarations to specify that the method
may throw certain exceptions.
• finally: The finally block is used to execute code that must be run regardless of whether
an exception was thrown or caught.
Lab Task
Task 1: Handling Checked Exceptions
Write a Java program that reads data from a non-existent file. Use a try-catch block to catch
and handle the FileNotFoundException that may occur.
39
BS (Software Engineering) 2023
Code Help:
import java.io.*;
super(message);
try {
} catch (FileNotFoundException e) {
40
BS (Software Engineering) 2023
try {
int divisor = 0;
} catch (ArithmeticException e) {
try {
throwCustomException();
} catch (CustomException e) {
try {
readDataFromFile();
} catch (IOException e) {
try {
41
BS (Software Engineering) 2023
} catch (FileNotFoundException e) {
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
} catch (IOException e) {
42
BS (Software Engineering) 2023
Theoretical Description
Graphical User Interfaces (GUIs) are essential for creating interactive Java applications. Java
provides the Abstract Window Toolkit (AWT) for building GUIs. AWT includes classes and
components for creating windows, buttons, labels, text fields, checkboxes, choice menus, lists,
and even basic graphics.
Lab Task
43
BS (Software Engineering) 2023
Code Help:
import java.awt.*;
import java.awt.event.*;
// Create a button
// Create a label
44
BS (Software Engineering) 2023
// Create a checkbox
choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
// Create a list
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
canvas.setSize(200, 200);
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
frame.add(textField);
frame.add(checkbox);
frame.add(choice);
frame.add(list);
frame.add(canvas);
45
BS (Software Engineering) 2023
frame.setSize(400, 300);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
label.setText("Button Clicked!");
});
frame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
46