Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
43 views13 pages

DSA Lab 03 SPRING 2022 SE

The document discusses object-oriented programming concepts in Java including classes, objects, and exception handling. It provides an example of defining a Circle class and creating Circle objects to represent circles of different radii. The example program constructs Circle objects, sets their radius values, and calculates their areas.

Uploaded by

Mehmood Sheikh
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)
43 views13 pages

DSA Lab 03 SPRING 2022 SE

The document discusses object-oriented programming concepts in Java including classes, objects, and exception handling. It provides an example of defining a Circle class and creating Circle objects to represent circles of different radii. The example program constructs Circle objects, sets their radius values, and calculates their areas.

Uploaded by

Mehmood Sheikh
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/ 13

USMAN INSTITUTE OF TECHNOLOGY

CS211 DATA STRUCTURES & ALGORITHMS


LAB 03
SPRING 2022

Name : _________________________________________
Roll No. : _________________ Section : ________________
Date : _________________________________________
Remarks : _________________________________________
Signature : _________________________________________
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

Experiment No. 03
Lab 03 – Understanding concepts of Classes, Objects and Exception Handling in JAVA .

Introduction
Having learned the material in earlier chapters, you are able to solve many programming problems using selections,
loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces
and large-scale software systems. Suppose you want to develop a GUI (graphical user interface, pronounced goo-ee)
as shown in Figure 3.1.
How do you program it?

FIGURE 3.1 The GUI objects are created from classes.


This lab begins the introduction of object-oriented programming, which will enable you to develop GUI and large-
scale software systems effectively.

Defining Classes for Objects


Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real
world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be
viewed as objects. An object has a unique identity, state, and behavior.
 The state of an object (also known as its properties or attributes) is represented by data fields with their
current values. A circle object, for example, has a data field radius, which is the property that characterizes
a circle. A rectangle object has data fields width and height, which are the properties that characterize a
rectangle.
 The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object
is to ask the object to perform an action. For example, you may define a method named getArea() for circle
objects. A circle object may invoke getArea() to return its area.
Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines
what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances
of a class. Creating an instance is referred to as instantiation. The terms object and instance are often interchangeable.
The relationship between classes and objects is analogous to that between an apple-pie recipe and apple pies. You can
make as many apple pies as you want from a single recipe. Figure 3.2 shows a class named Circle and its three objects.

FIGURE 3.2 A class is a template for creating objects.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 1
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


A Java class uses variables to define data fields and methods to define actions. Additionally, a class provides methods
of a special type, known as constructors, which are invoked to create a new object. A constructor can perform any
action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects.
Figure 3.3 shows an example of defining the class for circle objects.

FIGURE 3.3 A class is a construct that defines objects of the same type.

Main Class:
The Circle class is different from all of the other classes you have seen thus far. It does not have a main method and
therefore cannot be run; it is merely a definition for circle objects. The class that contains the main method will be
referred to in this book, for convenience, as the main class.

class diagram
The illustration of class templates and objects in Figure 3.2 can be standardized using UML (Unified Modeling
Language) notations. This notation, as shown in Figure 3.4, is called a UML class diagram, or simply a class diagram.
In the class diagram, the data field is denoted as:

FIGURE 3.4 Classes and objects can be represented using UML notations.
The constructor is denoted as
ClassName(parameterName: parameterType)
The method is denoted as
methodName(parameterName: parameterType): returnType

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 2
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Defining Classes and Creating Objects
This section gives two examples of defining classes and uses the classes to create objects Example 3.1 is a program
that defines the Circle class and uses it to create objects. To avoid a naming conflict with several improved versions
of the Circle class introduced later in this book, the Circle class in this example is named Circle1.
The program constructs three circle objects with radius 1.0, 25, and 125 and displays the radius and area of each of
the three circles. Change the radius of the second object to 100 and display its new radius and area.

EXAMPLE 3.1 TestCircle1.java


package TestCircle1;

public class TestCircle1{


/** Main method */
public static void main(String[] args) {
// Create a circle with radius 1.0
Circle1 circle1 = new Circle1();
System.out.println("The area of the circle of radius " + circle1.radius + " is " +
circle1.getArea());

// Create a circle with radius 25


Circle1 circle2 = new Circle1(25);
System.out.println("The area of the circle of radius " + circle2.radius + " is " +
circle2.getArea());

// Create a circle with radius 125


Circle1 circle3 = new Circle1(125);
System.out.println("The area of the circle of radius " + circle3.radius + " is " +
circle3.getArea());

// Modify circle radius


circle2.radius = 100;
System.out.println("The area of the circle of radius " + circle2.radius + " is " +
circle2.getArea() );
}
}

//Define the circle class with two constructors


class Circle1 {
double radius;

/** Construct a circle with radius 1 */


Circle1(){
radius = 1.0;
}

/** Construct a circle with a specified radius */


Circle1(double newRadius){
radius = newRadius;
}

/** Return the area of this circle */


double getArea(){
return radius * radius * Math.PI;
}
}
Output:

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 3
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

Client
The program contains two classes. The first of these, TestCircle1, is the main class. Its sole purpose is to test the
second class, Circle1. Such a program that uses the class is often referred to as a client of the class. When you run the
program, the Java runtime system invokes the main method in the main class.

Public Class
You can put the two classes into one file, but only one class in the file can be a public class. Furthermore, the public
class must have the same name as the file name. Therefore, the file name is TestCircle1.java, since TestCircle1 is
public.
The main class contains the main method (line 3) that creates three objects. As in creating an array, the new operator
is used to create an object from the constructor. new Circle1() creates an object with radius 1.0 (line 5), new
Circle1(25) creates an object with radius 25 (line 10), and new Circle1(125) creates an object with radius 125 (line
15).
These three objects (referenced by circle1, circle2, and circle3) have different data but the same methods. Therefore,
you can compute their respective areas by using the getArea() method. The data fields can be accessed via the
reference of the object using circle1.radius, circle2.radius, and circle3.radius, respectively. The object can invoke
its method via the reference of the object using circle1.getArea(), circle2.getArea(), and circle3.getArea(),
respectively.
These three objects are independent. The radius of circle2 is changed to 100 in line 20. The object’s new radius and
area is displayed in lines 21–22. There are many ways to write Java programs. For instance, you can combine the two
classes in the example into one, as shown in Example 3.2.

EXAMPLE 3.2 Circle1.java


public class Circle1{

/** Main method */


public static void main(String[] args) {
// Create a circle with radius 1.0
Circle1 circle1 = new Circle1();
System.out.println("The area of the circle of radius " + circle1.radius + " is "
+ circle1.getArea() );

// Create a circle with radius 25


Circle1 circle2 = new Circle1(25);
System.out.println("The area of the circle of radius " + circle2.radius + " is "
+ circle2.getArea());

// Create a circle with radius 125


Circle1 circle3 = new Circle1(125);
System.out.println("The area of the circle of radius " + circle3.radius + " is "
+ circle3.getArea());

// Modify circle radius


circle2.radius = 100;
System.out.println("The area of the circle of radius " + circle2.radius + " is "
+ circle2.getArea());
}

double radius;

/** Construct a circle with radius 1 */


Circle1(){
radius = 1.0;

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 4
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


}

/** Construct a circle with a specified radius */


Circle1(double newRadius){
radius = newRadius;
}

/** Return the area of this circle */


double getArea(){
return radius * radius * Math.PI;
}
}
Output

Since the combined class has a main method, it can be executed by the Java interpreter.

Constructing Objects Using Constructors


Constructors are a special kind of method. They have three peculiarities:
 A constructor must have the same name as the class itself.
 Constructors do not have a return type—not even void.
 Constructors are invoked using the new operator when an object is created. Constructors play the role of
initializing objects.
The constructor has exactly the same name as the defining class. Like regular methods, constructors can be overloaded
(i.e., multiple constructors can have the same name but different signatures), making it easy to construct objects with
different initial data values. It is a common mistake to put the void keyword in front of a constructor. For example,

public void Circle() {


}

In this case, Circle() is a method, not a constructor.


Constructors are used to construct objects. To construct an object from a class, invoke a constructor of the class using
the new operator, as follows:

new ClassName(arguments);

For example, new Circle() creates an object of the Circle class using the first constructor defined in the Circle class,
and new Circle(25) creates an object using the second constructor defined in the Circle class.
A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is referred to as a no-
arg or no-argument constructor.
A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined
in the class. This constructor, called a default constructor, is provided automatically only if no constructors are
explicitly defined in the class.

Accessing Objects via Reference Variables

Newly created objects are allocated in the memory. They can be accessed via reference variables.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 5
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Reference Variables and Reference Types
Objects are accessed via object reference variables, which contain references to the objects. Such variables are
declared using the following syntax:

ClassName objectRefVar;

A class is essentially a programmer-defined type. A class is a reference type, which means that a variable of the class
type can reference an instance of the class. The following statement declares the variable myCircle to be of the Circle
type:

Circle myCircle;

The variable myCircle can reference a Circle object. The next statement creates an object and assigns its reference to
myCircle:

myCircle = new Circle();

Using the syntax shown below, you can write a single statement that combines the declaration of an object reference
variable, the creation of an object, and the assigning of an object reference to the variable.

ClassName objectRefVar = new ClassName();

Here is an example:

Circle myCircle = new Circle();

The variable myCircle holds a reference to a Circle object.

Accessing an Object’s Data and Methods


After an object is created, its data can be accessed and its methods invoked using the dot operator (.), also known as
the object member access operator:
 objectRefVar.dataField references a data field in the object.
 objectRefVar.method(arguments) invokes a method on the object.
For example, myCircle.radius references the radius in myCircle, and myCircle.getArea() invokes the getArea
method on myCircle. Methods are invoked as operations on objects.
The data field radius is referred to as an instance variable, because it is dependent on a specific instance. For the same
reason, the method getArea is referred to as an instance method, because you can invoke it only on a specific instance.
The object on which an instance method is invoked is called a calling object.

Reference Data Fields and the Null Value


The data fields can be of reference types. For example, the following Student class contains a data field name of the
String type. String is a predefined Java class.

class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}

If a data field of a reference type does not reference any object, the data field holds a special Java value, null. null is
a literal just like true and false. While true and false are Boolean literals, null is a literal for a reference type. The
default value of a data field is null for a reference type, 0 for a numeric type, false

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 6
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a
method. The following code displays the default values of data fields name, age, isScienceMajor, and gender for a
Student object:

class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? "+ student.name);
System.out.println("age? "+ student.age);
System.out.println("isScienceMajor? "+ student.isScienceMajor);
System.out.println("gender? "+ student.gender);
}
}

The code below has a compile error, Fix the error and write output
Output

Execute the following code and comment the observation with output:

Output:

Modifiers or Visibility Modifiers


You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed
from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are
accessible by any class in the same package. This is known as package-private or package-access.
In addition to the public and default visibility modifiers, Java provides the private and protected modifiers for class
members. This section introduces the private modifier. The protected modifier will be introduced in §11.13, “The
protected Data and Methods.” The private modifier makes methods and data fields accessible only from within its
own class.
In addition to the public and default visibility modifiers, Java provides the private and protected modifiers for class
members. This section introduces the private modifier. The protected modifier will be introduced in §11.13, “The
protected Data and Methods.” The private modifier makes methods and data fields accessible only from within its
own class.
Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 7
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Let us create a new circle class with a private data-field radius and its associated accessor and mutator methods. The
class diagram is shown in Figure 3.5.

FIGURE 3.5 The Circle class encapsulates circle properties and provides get/set and other methods.

Exception-Handling Overview
To demonstrate exception handling, including how an exception object is created and thrown, we begin with an
example (Example 3.1.1) that reads in two integers and displays their quotient.
EXAMPLE 3.3 Quotient.java

If you entered 0 for the second number, a runtime error would occur, because you cannot divide an integer by 0. In
order to demonstrate the concept of exception handling, including how to create, throw,catch, and handle an exception,
we rewrite Listing 13.2 as shown in Example 3.4..

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 8
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

EXAMPLE 3.4 QuotientWithException.java

Output:

The finally Clause


Occasionally, you may want some code to be executed regardless of whether an exception occurs or is caught. Java
has a finally clause that can be used to accomplish this objective. The syntax for the finally clause might look like
this:

try {
statements;
}
catch (TheException ex) {
handling ex;
}
finally {
finalStatements;
}

When to Use Exceptions


The try block contains the code that is executed in normal circumstances. The catch block contains the code that is
executed in exceptional circumstances. Exception handling separates error-handling code from normal programming
tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires
more time and resources, because it requires instantiating a new exception object, rolling back the call stack, and
propagating the exception through the chain of methods invoked to search for the handler.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 9
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


An exception occurs in a method. If you want the exception to be processed by its caller, you should create an
exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw
or use exceptions. In general, common exceptions that may occur in multiple classes in a project are candidates for
exception classes. Simple errors that may occur in individual methods are best handled locally without throwing
exceptions.
When should you use a try-catch block in the code? Use it when you have to deal with unexpected error conditions.
Do not use a try-catch block to deal with simple, expected situations.

Answer the following questions:


1. Describe the relationship between an object and its defining class. How do you define a class? How do you
declare an object reference variable? How do you create an object? How do you declare and create an object
in one statement?
2. What is the purpose of declaring exceptions? How do you declare an exception, and where? Can you declare
multiple exceptions in a method header?
3. What is a checked exception, and what is an unchecked exception?
4. How do you throw an exception? Can you throw multiple exceptions in one throw statement?
5. What is the keyword throw used for? What is the keyword throws used for?
6. What are the differences between constructors and methods?
7. What is wrong in the following code?

8. What is the printout of the following code?

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 10
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________

9. Add the static keyword in the place of ? if appropriate.

10. What is an accessor method? What is a mutator method? What are the naming conventions for accessor
methods and mutator methods?
11. What are the benefits of data-field encapsulation?
12. What is wrong in the following code?

Debugging Exercise
There is one logic bug on one line of this code. Find it and fix it.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 11
Algorithms
Lab 03 – Understanding concepts of Classes, Objects and Exception
April 8, 2022 Handling in JAVA.

Student Name: ____________________________________ Roll No: ________________ Section: ______________


Programming Exercise
1. Write a program for calculator; for that create a class named BasicOpeartion that include four methods Add(),
Sub(), Multiply() & Divide() and create another class named Constants that include all constant value like
PI, Speed of Light etc, create another third class named ExtraOpreation that compute area of circle, area of
square, E=mc2 , etc.
2. Write a program that stores student information like: Roll#, Name, Department & Semester and display all.
3. Create an employee class. The member data should comprise an int for storing the employee number and a
float for storing the employee’s compensation. Member function should allow the user to enter this data and
display it. Write a main () that allow the user to enter data for three employees. And display it. (Hint: Use
loop).
4. Write a program to show the inheritance, polymorphism and encapsulation in JAVA. You can take the
example of Shapes. Shapes can be square, triangle, rectangle etc, then start calculating their areas and
circumference.
5. You have 3 different pairs of pets like cat, dog, parrots. Now use the concepts of JAVA object oriented
programming to show the behaviors of these pets like eats(), play(), run(), fly(), talk(), bark() etc
6. Construct a class of vehicles and now place different types of vehicles in it, some of the vehicles can use to
transport goods, some can be used for personal, some can take just 2 passengers, some can be able to take
22, 240, 320 etc Some can use roads, some uses tracks and some can fly. First make the diagram to show
which types of vehicles you are using then use proper pillars of OOPs. In all the above questions 1- 6 use
exceptional handling so your code can be secured.

Instructor: Asst. Prof. Syed Faisal Ali CS-211 | Data Structures & 12
Algorithms

You might also like