0% found this document useful (0 votes)
10 views46 pages

Object Oriented Programming SEOO 122 Lab Manual

This lab manual for Object-Oriented Programming (OOP) focuses on Java and includes practical exercises to enhance proficiency in OOP concepts such as classes, inheritance, polymorphism, encapsulation, and exception handling. Each lab is structured with clear objectives, theoretical descriptions, and hands-on tasks, starting from basic programming to more advanced topics. The manual also emphasizes the use of the Eclipse IDE and covers essential tools and technologies for Java development.

Uploaded by

imranjani395988
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)
10 views46 pages

Object Oriented Programming SEOO 122 Lab Manual

This lab manual for Object-Oriented Programming (OOP) focuses on Java and includes practical exercises to enhance proficiency in OOP concepts such as classes, inheritance, polymorphism, encapsulation, and exception handling. Each lab is structured with clear objectives, theoretical descriptions, and hands-on tasks, starting from basic programming to more advanced topics. The manual also emphasizes the use of the Eclipse IDE and covers essential tools and technologies for Java development.

Uploaded by

imranjani395988
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/ 46

LAB MANUAL

Object Oriented Programming


SEOO-122

DEPARTMENT OF SOFTWARE ENGINEERING


FACULTY OF ENGINEERING & CS
NATIONAL UNIVERSITY OF MODERN LANGUAGES
ISLAMABAD
BS (Software Engineering) 2023

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.

Polymorphism: Discover how polymorphism enhances code flexibility and reusability.

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.

Exception Handling: Master the techniques of handling exceptions gracefully in Java.

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

LAB 1: Introduction to Eclipse, Writing Java programs, Basic


Programming Structure of Java

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.

Task 2: Writing Your First Java Program


• Create a new Java class called "HelloWorld."
• Write a simple Java program that displays "Hello, World!" on the console.
• Save the file and run the program to verify its output.

Task 3: Understanding the Basic Structure


• Analyze the Java program you wrote in Task 2.
• Identify the main components of a Java program, including the class declaration,
method declaration, and statements.

Task 4: Experimenting with Output


• Modify the Java program to display a different message of your choice.

4
BS (Software Engineering) 2023

• Run the program again to observe the updated output.

Task 5: Comments and Documentation


• Add comments to your Java program to explain its functionality.
• Understand the importance of code documentation for program clarity and
maintenance.

Code Help:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Welcome to Java Programming!");
}
}

5
BS (Software Engineering) 2023

LAB 2: Methods, Method signatures, Parameters and Arguments


Objectives
In this lab, you will learn about methods in Java, explore method signatures, and understand
the concepts of parameters and arguments.

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.

Task 2: Method Signatures


• Understand the components of a method signature: method name, return type, and
parameters.
• Modify the add method's signature to include a description of its purpose.
• Explore how changing the method signature affects its usage.

Task 3: Method Parameters and Arguments


• Analyze the difference between method parameters and method arguments.
• Modify the add method to take two double parameters instead of integers.
• Call the add method with different sets of arguments to observe how it handles different
data types.

Task 4: Overloading Methods


• Create an overloaded version of the add method that accepts three integers and returns
their sum.
• Call the overloaded method with different numbers of arguments.
• Discuss the concept of method overloading and its advantages.

6
BS (Software Engineering) 2023

Task 5: Returning Values from Methods


• Create a new method named findMax within the "Calculator" class. This method should
accept an array of integers and return the maximum value from the array.
• Call the findMax method and display the result.

Task 6: Method Documentation


• Add comments to your methods to describe their functionality and parameters.
• Emphasize the importance of clear and concise method documentation.

Code Help:
// Task 1: Simple Method
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();
int result = calculator.add(5, 7);
System.out.println("Result: " + result);
}
}

// Task 4: Overloaded Methods


public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}

public int add(int num1, int num2, int num3) {


return num1 + num2 + num3;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 7);
int sum2 = calculator.add(2, 4, 6);

7
BS (Software Engineering) 2023

System.out.println("Sum 1: " + sum1);


System.out.println("Sum 2: " + sum2);
}
}

// Task 5: Returning Values from Methods


public class Calculator {
public int findMax(int[] numbers) {
int max = Integer.MIN_VALUE;
for (int number : numbers) {
if (number > max) {
max = number;
}
}
return max;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();
int[] numbers = { 10, 5, 8, 22, 13 };
int maxNumber = calculator.findMax(numbers);
System.out.println("Maximum Number: " + maxNumber);
}
}

8
BS (Software Engineering) 2023

LAB 3: Classes and Objects, Properties, and Behaviour


Objectives
In this lab, you will dive into the fundamental concepts of object-oriented programming in
Java, specifically focusing on classes, objects, properties (attributes), and behavior (methods).
You will learn how to design and create classes, instantiate objects from those classes, define
properties to represent the state of objects, and implement methods to specify their behavior.

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.

Behavior (Methods): Behavior in object-oriented programming is defined through methods.


Methods are functions or procedures associated with a class that describe the actions or
operations an object can perform. In this lab, you will implement two methods: introduce and
birthday. The introduce method allows a person to introduce themselves, and the birthday
method increments a person's age.

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.

Task 2: Instantiating Objects

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.

Task 3: Adding Behavior


• Add a method named introduce to the "Person" class. This method should print a
message introducing the person by name and age.
• Call the introduce method for both persons you created in Task 2.

Task 4: Modifying Properties


• Add a method named birthday to the "Person" class. This method should increment
the person's age by 1.
• Call the birthday method for one of the persons and print their updated age.

Task 5: Class Documentation


• Add comments to your class, methods, and properties to document their functionality
and purpose.
• Explain the concept of encapsulation and how it helps maintain data integrity.

Code Help:
// Task 1: Creating a Class

public class Person {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

public void introduce() {

System.out.println("Hello, my name is " + name + " and I am " + age + "


years old.");

10
BS (Software Engineering) 2023

public void birthday() {

age++;

// Getter and Setter methods for encapsulation

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

this.age = age;

// Task 2: Instantiating Objects

public class Main {

public static void main(String[] args) {

Person person1 = new Person("Alice", 25);

Person person2 = new Person("Bob", 30);

person1.introduce();

person2.introduce();

11
BS (Software Engineering) 2023

person1.birthday();

System.out.println(person1.getName() + "'s new age: " + person1.getAge());

12
BS (Software Engineering) 2023

LAB 4: Constructors of classes and their utility, Constructor


Overloading
Objectives
In this lab, you will explore the concept of constructors in Java classes. Constructors are special
methods used for initializing objects when they are created. You will learn how to define
constructors, their role in setting initial object states, and how to overload constructors to
provide different initialization options.

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.

Parameterized Constructors: In addition to default constructors, you can define


parameterized constructors that accept arguments. Parameterized constructors allow you to
create objects with specific initial states by passing values when the object is instantiated.

Constructor Overloading: Constructor overloading is a practice where a class has multiple


constructors with different parameter lists. Each overloaded constructor provides a different
way to initialize objects based on the provided arguments.

Lab Task
Task 1: Default Constructor
Create a new Java class named "Product."
public class Product {

// Properties

private String productName;

13
BS (Software Engineering) 2023

private double price;

private int quantity;

// Default Constructor

public Product() {

productName = "Unknown";

price = 0.0;

quantity = 0;

// Other methods and constructors go here...

Task 2: Parameterized Constructor


Modify the "Product" class by adding a parameterized constructor.
// Parameterized Constructor

public Product(String name, double initialPrice, int initialQuantity) {

productName = name;

price = initialPrice;

quantity = initialQuantity;

Task 3: Constructor Overloading


Implement constructor overloading in the "Product" class.
// Constructor Overloading

public Product(String name) {

productName = name;

price = 0.0;

quantity = 0;

14
BS (Software Engineering) 2023

Task 4: Object Instantiation


In the main method of another class, instantiate objects of the "Product" class using each of
the defined constructors.
public class Main {

public static void main(String[] args) {

// Using Default Constructor

Product defaultProduct = new Product();

// Using Parameterized Constructor

Product customProduct = new Product("Laptop", 999.99, 5);

// Using Overloaded Constructor

Product namedProduct = new Product("Smartphone");

Task 5: Display Information


Write methods in the "Product" class to display information about the product
objects.

// Display Product Information

public void displayProductInfo() {

System.out.println("Product Name: " + productName);

System.out.println("Price: $" + price);

System.out.println("Quantity: " + quantity);

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 {

public static void main(String[] args) {

Product defaultProduct = new Product();

15
BS (Software Engineering) 2023

Product customProduct = new Product("Laptop", 999.99, 5);

Product namedProduct = new Product("Smartphone");

// Display Product Information

defaultProduct.displayProductInfo();

customProduct.displayProductInfo();

namedProduct.displayProductInfo();

16
BS (Software Engineering) 2023

LAB 5: Static Variables and Static Methods, Basic concept of


Final Keyword
Objectives
In this lab, you will explore the concepts of static variables and static methods in Java classes.
Additionally, you will learn about the "final" keyword and its usage in Java.

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

Task 1: Static Variables

Create a Java class named "Counter" that contains a static integer variable named "count."
Initialize "count" to 0.

public class Counter {

// Static Variable

static int count = 0;

// Other methods go here...

17
BS (Software Engineering) 2023

Task 2: Static Methods

In the "Counter" class, create a static method named "incrementCount" that increments the
"count" variable by 1 each time it is called.

// Static Method

static void incrementCount() {

count++;

Task 3: Final Keyword

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).

public class Circle {

// Final Variable

final double PI = 3.14159;

// Other methods and variables go here...

Task 4: Testing Static Variables and Methods

In the main method of another class, create instances of the "Counter" class and test the static
variable and static method.

public class Main {

public static void main(String[] args) {

// Testing Static Variables and Methods

Counter.incrementCount();

Counter.incrementCount();

System.out.println("Count: " + Counter.count);

Task 5: Testing Final Variable

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.

public class Main {

public static void main(String[] args) {

// Testing Final Variable

Circle circle = new Circle();

double radius = 5.0;

double area = circle.PI * radius * radius;

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

19
BS (Software Engineering) 2023

LAB 6: Encapsulation and its implementation, Access modifiers,


Data Hiding
Objectives
In this lab, you will explore the concept of encapsulation in Java, understand the use of access
modifiers, and practice data hiding through practical implementation.

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.

public class Student {

// Private data members

private String name;

private int rollNumber;

20
BS (Software Engineering) 2023

private double gpa;

// Public methods for encapsulation

public void setName(String name) {

this.name = name;

public String getName() {

return name;

// Implement similar methods for roll number and GPA.

// Other methods and variables go here...

Task 2: Access Modifiers


In the "Student" class, use appropriate access modifiers to ensure that data members can only
be accessed through the public methods defined in Task 1.

Task 3: Data Hiding


In the main method of another class, create instances of the "Student" class and demonstrate
the use of public methods to set and retrieve student information. Emphasize the concept of
data hiding.
public class Main {

public static void main(String[] args) {

// Creating Student objects

Student student1 = new Student();

// Setting student information using public methods

student1.setName("Alice");

student1.setRollNumber(101);

student1.setGPA(3.8);

21
BS (Software Engineering) 2023

// Retrieving and displaying student information

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

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

System.out.println("GPA: " + student1.getGPA());

22
BS (Software Engineering) 2023

LAB 7: Basic concept of inheritance, Parent and Child Classes


Objectives
In this lab, you will explore the fundamental concept of inheritance in Java, creating parent and
child classes to demonstrate how attributes and methods can be inherited from a base class.

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

Task 1: Parent Class


Create a Java class named "Vehicle" to represent a basic vehicle. Include attributes such as
"make" and "model," and a method to display vehicle information.

public class Vehicle {

// Attributes

private String make;

private String model;

// Constructor

public Vehicle(String make, String model) {

this.make = make;

this.model = model;

23
BS (Software Engineering) 2023

// Method to display vehicle information

public void displayInfo() {

System.out.println("Make: " + make);

System.out.println("Model: " + model);

Task 2: Child Class


Create a Java class named "Car" as a child class of "Vehicle." The "Car" class should inherit
the "make" and "model" attributes and the "displayInfo" method from the parent class.
Additionally, add attributes and methods specific to a car, such as "year" and "fuelType."

public class Car extends Vehicle {

// Additional attributes

private int year;

private String fuelType;

// Constructor

public Car(String make, String model, int year, String fuelType) {

super(make, model); // Call the parent class constructor

this.year = year;

this.fuelType = fuelType;

// Method to display car information (including inherited attributes)

public void displayCarInfo() {

displayInfo(); // Call the inherited method to display make and model

System.out.println("Year: " + year);

System.out.println("Fuel Type: " + 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.

public class Main {

public static void main(String[] args) {

// Creating a Car object

Car myCar = new Car("Toyota", "Camry", 2022, "Gasoline");

// Display car information using the child class method

myCar.displayCarInfo();

25
BS (Software Engineering) 2023

LAB 8: Polymorphism through Method Overriding, Use of


Protected Keyword
Objectives
In this lab, you will explore the concept of method overriding in Java, allowing a child class to
provide a specific implementation for a method inherited from its parent class. Additionally,
you will learn how to use the protected keyword to control access to class members.

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

Task 1: Parent Class


Create a Java class named "Shape" to represent a basic geometric shape. Include a method
named calculateArea that calculates the area of the shape. Mark this method as protected.

public class Shape {

// Method to calculate the area (protected)

protected double calculateArea() {

return 0.0; // Default implementation for base class

26
BS (Software Engineering) 2023

Task 2: Child Class

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.

public class Circle extends Shape {

// Additional attribute

private double radius;

// Constructor

public Circle(double radius) {

this.radius = radius;

// Override the calculateArea method

@Override

protected double calculateArea() {

return Math.PI * Math.pow(radius, 2);

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.

public class Main {

public static void main(String[] args) {

// Creating Circle objects

Circle circle1 = new Circle(5.0);

Circle circle2 = new Circle(7.5);

27
BS (Software Engineering) 2023

// Calculate and display areas using method overriding

System.out.println("Area of Circle 1: " + circle1.calculateArea());

System.out.println("Area of Circle 2: " + circle2.calculateArea());

28
BS (Software Engineering) 2023

LAB 9: Use of Final Keyword in Inheritance, Final classes, Final


methods
Objectives
In this lab, you will explore the use of the final keyword in Java, which has several implications
for class inheritance. You will learn how to declare final classes, final methods, and understand
their significance in object-oriented programming.

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

public final class FinalClass {

// A simple method

public void displayMessage() {

System.out.println("This is a final class.");

Task 2: Attempt to Inherit from Final Class


Create another Java class named "SubClass" and attempt to inherit from the "FinalClass."
Explain the error message you receive when trying to extend a final class.

29
BS (Software Engineering) 2023

// SubClass.java

public class SubClass extends FinalClass {

// This will result in a compilation error

Task 3: Create a Class with Final Method


Create a Java class named "ParentClass" with a final method.

// ParentClass.java

public class ParentClass {

// A final method

public final void finalMethod() {

System.out.println("This is a final method.");

Task 4: Attempt to Override Final Method


Create a Java class named "ChildClass" that attempts to override the final method of the
"ParentClass." Explain the error message you receive when trying to override a final method.

// ChildClass.java

public class ChildClass extends ParentClass {

// This will result in a compilation error

30
BS (Software Engineering) 2023

LAB 10: Object Casting and Dynamic Method Dispatch


Objectives
In this lab, you will explore the concepts of object casting and dynamic method dispatch in
Java. You will learn how to cast objects between classes, utilize polymorphism, and understand
how method calls are determined at runtime.

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.

Dynamic Method Dispatch: Dynamic method dispatch is a mechanism by which the


appropriate method to be called is determined at runtime. It is a fundamental concept in
achieving runtime polymorphism in Java.

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

public class Parent {

public void display() {

System.out.println("This is the Parent class.");

// Child.java

public class Child extends Parent {

@Override

public void display() {

System.out.println("This is the Child class.");

31
BS (Software Engineering) 2023

Task 2: Perform Object Casting


In the main Java class, create instances of both "Parent" and "Child" classes. Perform object
casting to call the display method of both classes and observe the dynamic method dispatch in
action.

// Main.java

public class Main {

public static void main(String[] args) {

Parent parent = new Parent();

Child child = new Child();

// Perform object casting

Parent obj1 = (Parent) child;

Parent obj2 = parent;

// Call the display method

obj1.display(); // Should call Child class's display method

obj2.display(); // Should call Parent class's display method

32
BS (Software Engineering) 2023

LAB 11: Abstract Classes and Abstract Methods


Objectives
In this lab, you will delve into the concept of abstract classes and abstract methods in Java.
You will learn how to declare abstract classes, define abstract methods, and implement them
in concrete subclasses.

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

Task 1: Create an Abstract Class


Create an abstract class named "Shape." Define an abstract method calculateArea() in the
"Shape" class. This method should return a double and represent the area of the shape.

// Shape.java

public abstract class Shape {

public abstract double calculateArea();

Task 2: Implement Concrete Subclasses

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

public class Circle extends Shape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double calculateArea() {

return Math.PI * radius * radius;

// Rectangle.java

public class Rectangle extends Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double calculateArea() {

return length * width;

Task 3: Test the Abstract Classes

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

public class Main {

public static void main(String[] args) {

Shape circle = new Circle(5.0);

Shape rectangle = new Rectangle(4.0, 6.0);

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

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

35
BS (Software Engineering) 2023

LAB 12: Interfaces in Java, Implementing interfaces


Objectives
In this lab, you will explore the concept of interfaces in Java. You will learn how to define
interfaces, implement them in classes, and work with variables declared in interfaces.

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

public interface GeometricShape {

double calculateArea();

double calculatePerimeter();

Task 2: Implement the Interface

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

public class Circle implements GeometricShape {

private double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double calculateArea() {

return Math.PI * radius * radius;

@Override

public double calculatePerimeter() {

return 2 * Math.PI * radius;

Task 3: Implement a Variable in an Interface


Modify the "GeometricShape" interface to include a constant variable PI and use it in the
calculateArea() and calculatePerimeter() methods.

// GeometricShape.java

public interface GeometricShape {

double PI = 3.14159265359;

double calculateArea();

double calculatePerimeter();

37
BS (Software Engineering) 2023

Task 4: Test the Interface and Class


In the main Java class, create an instance of the "Circle" class, call its calculateArea() and
calculatePerimeter() methods, and display the results.

// Main.java

public class Main {

public static void main(String[] args) {

GeometricShape circle = new Circle(5.0);

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

System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

38
BS (Software Engineering) 2023

LAB 13: Exception Handling Fundamentals, Types of Exceptions,


Using exception clauses
Objectives
In this lab, you will delve into the fundamentals of exception handling in Java. You will explore
various types of exceptions, learn to use exception clauses such as try, catch, throw, throws,
and finally, and gain hands-on experience in handling exceptions effectively.

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.

Task 2: Handling Unchecked Exceptions


Write a Java program that divides two numbers. Handle the ArithmeticException that may
occur if the second number is zero.

39
BS (Software Engineering) 2023

Task 3: Throwing Exceptions


Create a custom exception class named "CustomException" that extends Exception. Write a
method that throws this custom exception. Demonstrate how to use the throw statement to
throw this exception.

Task 4: Using throws Clause


Write a Java method that reads data from a file. Use the throws clause to indicate that the
method may throw IOException. Call this method from the main program.

Task 5: Using finally Block


Write a Java program that opens a resource (e.g., a file or network connection) inside a try
block. Close the resource inside a finally block to ensure that it is properly released, even if
an exception occurs.

Code Help:

import java.io.*;

class CustomException extends Exception {

public CustomException(String message) {

super(message);

public class ExceptionHandlingDemo {

public static void main(String[] args) {

try {

// Task 1: Handling Checked Exceptions

FileReader fileReader = new FileReader("non_existent_file.txt");

} catch (FileNotFoundException e) {

System.err.println("Task 1: Caught FileNotFoundException: " +


e.getMessage());

40
BS (Software Engineering) 2023

try {

// Task 2: Handling Unchecked Exceptions

int dividend = 10;

int divisor = 0;

int result = dividend / divisor;

System.out.println("Task 2: Result: " + result);

} catch (ArithmeticException e) {

System.err.println("Task 2: Caught ArithmeticException: " +


e.getMessage());

// Task 3: Throwing Exceptions

try {

throwCustomException();

} catch (CustomException e) {

System.err.println("Task 3: Caught CustomException: " +


e.getMessage());

// Task 4: Using throws Clause

try {

readDataFromFile();

} catch (IOException e) {

System.err.println("Task 4: Caught IOException: " + e.getMessage());

// Task 5: Using finally Block

FileInputStream fileInputStream = null;

try {

fileInputStream = new FileInputStream("sample.txt");

// Code to read data from the file

System.out.println("Task 5: File opened and data read successfully.");

41
BS (Software Engineering) 2023

} catch (FileNotFoundException e) {

System.err.println("Task 5: Caught FileNotFoundException: " +


e.getMessage());

} finally {

try {

if (fileInputStream != null) {

fileInputStream.close();

System.out.println("Task 5: File closed in the finally


block.");

} catch (IOException e) {

System.err.println("Task 5: Error while closing the file: " +


e.getMessage());

// Task 3: Throwing Exceptions

public static void throwCustomException() throws CustomException {

throw new CustomException("Custom exception thrown in Task 3.");

// Task 4: Using throws Clause

public static void readDataFromFile() throws IOException {

// Code to read data from a file

throw new IOException("IOException in Task 4: Simulated file read


error.");

42
BS (Software Engineering) 2023

LAB 14: Graphical User Interface Components, Introduction to


AWT, AWT classes
Objectives
In this lab, you will learn the fundamentals of creating graphical user interface components
using AWT in Java. You will create a simple GUI window with various components and work
with basic graphics.

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

Task 1: Create a GUI Window with Components


• Create a Java program that opens a GUI window.
• Add the following components to the window:
• A button with the label "Click Me!"
• A label displaying "Hello, GUI World!"
• A text field with the initial text "Type something here"
• A checkbox with the label "Check this"
• A choice (dropdown) menu with three options
• A list with at least three items
• Set an appropriate layout manager for the window, such as FlowLayout.
• Make the window visible to the user.

Task 2: Handle Button Click Event


• Add an event listener to the button created in Task 1.
• When the button is clicked, change the label text to "Button Clicked!"

Task 3: Add Drawing Canvas


• Create a canvas component for drawing.
• Set the size of the canvas to 200x200 pixels.

43
BS (Software Engineering) 2023

• Add the canvas to the GUI window.


• Implement basic drawing on the canvas, such as drawing shapes or lines.

Task 4: Implement Window Close Action


• Add a window listener to handle the window close action.
• When the user attempts to close the window, the program should exit gracefully.

Task 5: Compile and Run


• Compile your Java program.
• Run the program to see the GUI window with components and the drawing canvas.
• Test the button's click event and observe the label change.

Task 6: Experiment and Enhance


• Experiment with the GUI components.
• Enhance the program by adding more components, changing layouts, or implementing
additional functionality.

Code Help:

import java.awt.*;

import java.awt.event.*;

public class GUIComponentsDemo {

public static void main(String[] args) {

// Create a new frame (window)

Frame frame = new Frame("GUI Components Demo");

// Create a button

Button button = new Button("Click Me!");

// Create a label

Label label = new Label("Hello, GUI World!");

// Create a text field

44
BS (Software Engineering) 2023

TextField textField = new TextField("Type something here");

// Create a checkbox

Checkbox checkbox = new Checkbox("Check this");

// Create a choice (dropdown) menu

Choice choice = new Choice();

choice.add("Option 1");

choice.add("Option 2");

choice.add("Option 3");

// Create a list

List list = new List();

list.add("Item 1");

list.add("Item 2");

list.add("Item 3");

// Create a canvas for drawing

Canvas canvas = new Canvas();

canvas.setSize(200, 200);

// Set layout manager for the frame

frame.setLayout(new FlowLayout());

// Add components to the frame

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

// Set frame properties

frame.setSize(400, 300);

frame.setVisible(true);

// Add an event listener to the button

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setText("Button Clicked!");

});

// Add a window listener to handle window close event

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

46

You might also like