0% found this document useful (0 votes)
9 views19 pages

Java Arrays: 1D & 2D Concepts Explained

The document contains lecture notes for Object-Oriented Programming covering one-dimensional and two-dimensional arrays in Java, including their declaration, creation, and usage. It provides examples of programs demonstrating array functionalities and explains concepts such as variable declaration, data types, and the main method structure in Java. Additionally, it discusses Java identifiers, comments, and the assignment operator.

Uploaded by

abdulrehman12uni
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)
9 views19 pages

Java Arrays: 1D & 2D Concepts Explained

The document contains lecture notes for Object-Oriented Programming covering one-dimensional and two-dimensional arrays in Java, including their declaration, creation, and usage. It provides examples of programs demonstrating array functionalities and explains concepts such as variable declaration, data types, and the main method structure in Java. Additionally, it discusses Java identifiers, comments, and the assignment operator.

Uploaded by

abdulrehman12uni
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

DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND

TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd


Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 3 Page: 1/11 Roll Number_________________________
Name____________________________ Topic Covered : One-dimensional Arrays (1D Array), Two
– dimensional Array (2D -Array) , Introduction to JAVA String , Local variable type inference , Java
User Input (Scanner class) . ARRAYS Java provides a data structure, the array, which stores a
fixed -size sequential collection of elements of the same type. An array is used to store a collection
of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables. DECLARING ARRAY VARIABLES To use an array in a program,
you must declare a variable to reference the array, and you must specify the type of array the
variable can reference. Here is the syntax for declaring an array variable: dataType[] arrayRefVar;
or dataType arrayRefVar[]; The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers. You can declare multiple arrays of the same data type in one state ment by inserting
a comma after each array name, using this syntax: dataType[] arrayName1, arrayName2;
CREATING ARRAYS You can create an array by using the new operator w ith the following syntax:
arrayRefVar = new dataType[arraySize]; The a bove statement does two things: • It creates an
array using new dataType[arraySize]. • It assigns the reference of the newly created array to the
variable arrayRefVar. Declaring an array variable, creating an array, and assigning the reference of
the array to the variable can be combined in one statement, as shown below: dataType[]
arrayRefVar = new dataType[arraySize]; DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 3 Page: 2/11 Roll
Number_________________________ Name____________________________ For Example:
int[] arr = new int[10]; Alternatively yo u can create arrays as follows: dataType[] arrayRefVar =
{value0, value1, ..., valuek}; The number of elements in the array is determined by the number of
values in the initialization list. The values can be an expression, for example, nine and nine + 2. For
example, this statement declares and instantiates an array of odd numbers: int nine = 9; int[]
oddNumbers = {1 ,3 ,5 ,7 ,nine ,nine+2, 13}; PROGRAM 1 : Demonstrate a one -dimensional array.
class Array { public static void main(String args[]) { int month_days[]; month_days = new int[12];
month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4]
= 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30;
month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; [Link]("April has " +
month_days[3] + " days."); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 3 Page: 3/11 Roll Number_________________________
Name____________________________ PROGRAM 2 : Creates an initialized array of integers:
class AutoArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 }; [Link]("April has " + month_days[3] + " days."); } } PROGRAM 3
: Average an array of values. class Average { public static void main(String args[]) { double nums[] =
{10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; int i; for(i=0; i<5; i++) result = result + nums[i];
[Link]("Average is " + result / 5); } } ACCESSING ARRAY ELEM ENTS Elements of an
array are accessed using index, within the array . The index of the first element in the array is
always 0 and the index of the last element is always 1 less than the number of elements. Arrays
have a read -only, integer instance variable, length, which holds the number of elements in the
array. To access the number of elements in an array named arrayName, use this syntax: [Link]
Thus, to access the last element of an array, use this syntax: arr [[Link] – 1 ] DEPARTMENT
OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY
UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025
OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 3
Page: 4/11 Roll Number_________________________ Name____________________________
PROGRAM 4 : Simple Array class TestArray { public static void main(String[] args) { double[] myList
= {1.9, 2.9, 3.4, 3.5}; for (int i = 0; i < [Link]; i++) { [Link](myList[i] + " "); } double
total = 0; for (int i = 0; i < [Link]; i++) { total += myList[i]; } [Link]("Total is " +
total); } } MULTIDIMENSIONAL ARRAYS IN JAVA Multidimensional Arrays can be defined in
simple words as array of arrays. TWO – DIMENSIONAL ARRAY (2D -ARRAY) Two – dimensional
array is the simplest form of a multidimensional array. A two – dimensional array can be seen as an
array of one – dimensional array for easier understanding. Syntax to Declare Multidimensional
Array in Java: dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType
arrayRefVar[][]; (or) dataType []arrayRefVar[]; Example to instantiate Multidimensional Array in
Java int[][] arr=new int[3][3]; DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 3 Page: 5/11 Roll Number_________________________
Name____________________________ When you allocate memory for a multidimensional array,
you need only specify the memory for the first (leftmost) dimension. You can allocate the rema ining
dimensions separately. For example, this following code allocates memory for the first dimension of
twoD when it is declared. It allocates the second dimension manually. int twoD[][] = new int[3][];
twoD[0] = new int[5]; twoD[1] = new int[5]; twoD[2] = new int[5]; When you allocate dimensions
manually, you do not need to allocate the same number of elements for each dimension. You can
create a two -dimensional array in which the sizes of the second dimension are unequal.
PROGRAM 5 : Demonstrate a two-dimensional array. class TwoDArray { public static void
main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) {
twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) [Link](twoD[i][j] + " ");
[Link](); } } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 3 Page: 6/11 Roll Number_________________________
Name____________________________ PROGRAM 6 : Declaring and initializing 2D array class
TestArray{ public static void main(String args[]){ int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; for(int
i=0;i<3;i++){ for(int j=0;j<3;j++){ [Link](arr[i][j]+" "); } [Link](); } } } PROGRAM
7 : Manually allocate differing size second dimensions. class TwoDAgain { public static void
main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] =
new int[3]; twoD[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j javac [Link] This will
compile your code. If there are no errors in the code, the command prompt will take you to the next
line. Now, type "java MyClass" to run the file . Make sure to type M and C in uppercase as in class
name : D:\JAVA PROG > java MyClass The output will be shown: Hello World EXAMPLE
EXPLAINED Every line of code that runs in Java must be inside a class. In our example, we named
the class MyClass . A class should always start with an uppercase first letter. If several words are
used to form a name of the class each inner words first letter should be in Upper Case. Example
class MyFirstJavaClass Note : Java is case -sensitive: "Hello" and "hello" has different meani ng.
THE MAIN METHOD The main() method is required and you will see it in every Java program:
public static void main(String[] args) Any code inside the main() method will be executed every
program must contain the main() method. A block, which consists of 0, 1, or more statements, starts
with a left curly brace ({) and ends with a right curly brace (}). Blocks are required for class and
method definitions and can be used anywhere else in the program that a statement is legal. Exampl
e has two blocks: the class definition and t he main method definition . As you can see, nesting
blocks within blocks is perfectly legal. The main block is nested completely within the class
definition block. [Link]() Inside the main() method, w e can use the println()
method to print a line of text to the screen: DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (1st Semester) 2025 OBJECT ORIENTED PROGRAMMING
(320/321 ) Instructor: Junaid Javed Korai WEEK. 1 Page: 5/9
Name____________________________ Roll Number_________________________ JAVA
COMMENTS Comments can be used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code. Single -line comments starts with
two forward slashes ( Any text between Multi -line comments start with . Any text between will be
ignored by Java. JAVA IDENTIFIERS All Java variables , method names, class names and other
data members must be identified with unique names . These unique names are called identifiers .
VARIABLES Java allows you to refer to the data in a program by defining variables, which are
named locations in memory where you can store values. A variable can store one data value at a
time, but that value might change as the program executes . Identifiers can be short names (like x
and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing
names for variables (unique identifiers) are : ■ Names can contain letters, digits, underscores, and
dollar signs ■ Names should begin with a letter ■ Names can also begin with $ and _ ■ Names are
case sensitive ("myVar" and "myvar" are different variables) ■ Names should start with a lowercase
letter and it cannot contain whitespace . If the variable name consists of more than one word, then
each word after the first should begin with a capital letter. For example, these identifiers are
conventional Java variable names: number1, highScore, booksToRead, ageInYe ars, and xAxis. ■
Reserved words (like Java keywords, such as int or String) cannot be used as names DATA
TYPES Java supports eight primitive data types: byte, short, int, long, float, double, char, and
boolean. They are called primitive data types because they are part of the core Java language. The
data type you specify for a variable tells the compiler how much memory to allocate and the format
in which to store the data. DECLARING VARIABLES Every variable must be given a name and a
data type before it c an be used. This is called declaring a variable. The syntax for declaring a
variable is: datatype identifier; OR datatype identifier1, identifier2, ...; DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (1st Semester) 2025 OBJECT
ORIENTED PROGRAMMING (320/321 ) Instructor: Junaid Javed Korai WEEK. 1 Page: 6/9
Name____________________________ Roll Number_________________________ INTEGER
DATA TYPES This group includes byte , short , int, and long , which are for whole -valued signed
numbers. Integer Data Type Size in Bytes Min Value Max Value Byte 1 -128 127 Short 2 -32,768
32,767 Int 4 - 2,147,483,648 2,147,483,647 Long 8 -9,223,372,036,854,775,808
9,223,372,036,854,775,807 FLOATING -POINT DATA TYPES This group includes float and double
, which represent numbers with fractional precision. Floating -point Data Type Size in Bytes Max
Positive Non Zero Value Max Value Float 4 1.40239846 x 10-45 3.40282347 x 1038 Double 8
4.9406564584124654 x 10-324 1.7976931348623157 x 10308 CHARACTER DATA TYPE
Character Data Type Size in Bytes Min Value Max Value Char 2 The character encoded as 0000,
the null character The value FFFF which is a special code for “not a character” BOOLEAN DATA
TYPE Boolean Data Type The boolean data type can store only two values, which are expressed
using the Java reserved words true and false . THE ASSIGNMENT OPERA TOR, INITIAL
VALUES, AND LITERALS When you declare a variable, you can also assign an initial value to the
data. To do that, use th e assignment operator (=) with the following syntax: datatype variableName
= initialV alue; This statement is read as “variableName gets initialValue”. Or datatype variable 1 =
initialV alue1, variable 2 = initialV alue2 ; Notice that assignment is right to left. The initial value is
assigned to the variable. DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (1st Semester) 2025 OBJECT ORIENTED PROGRAMMING (320/321 )
Instructor: Junaid Javed Korai WEEK. 1 Page: 7/9 Name____________________________ Roll
Number_________________________ PROGRAM 2: Calculates area of Circle class AreaOfCircle
{ public static void main(String[] args) { final double PI = 3.14159; double radius; double area; radius
= 3.5; area = PI * radius * radius; [Link]( "The area of Circle is " + area ); } } PROGRAM
3: Demonstrates long data type. Computes the number of miles that light will travel in a specified
number of days. class Light { public static void main(String args[]) { int lightspeed; long days; long
seconds; long distance; lightspeed = 186000; days = 1000; seconds = days * 24 * 60 * 60; distance
= lightspeed * seconds; [Link]("In " + days); [Link](" days light wil l travel about
"); [Link](distance + " miles."); } } DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (1st Semester) 2025 OBJECT ORIENTED PROGRAMMING
(320/321 ) Instructor: Junaid Javed Korai WEEK. 1 Page: 8/9
Name____________________________ Roll Number_________________________ PROGRAM
4: Demonstrates char variables behave like integers. class CharDemo2 { public static void
main(String args[]) { char ch1 = 'X'; [Link]("ch1 contains " + ch1); ch1++;
[Link]("ch1 is now " + ch1); } } PROGRAM 5: Demonstrate boolean values. class
BoolTest { public static void main(String args[]) { boolean b; b = false; [Link]("b is " + b);
b = true; [Link]("b is " + b); if(b) [Link]("This is executed."); b = false; if(b)
[Link]("This is not executed."); [Link]("10 > 9 is " + (10 > 9)); } } PROGRAM
6 : Demonstrate dynamic initialization. class DynInit { public static void main(String args[]) { double
a = 3.0, b = 4.0; double c = [Link](a * a + b * b); [Link]("Hypotenuse is " + c); } }
DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (1st
Semester) 2025 OBJECT ORIENTED PROGRAMMING (320/321 ) Instructor: Junaid Javed Korai
WEEK. 1 Page: 9/9 Name____________________________ Roll
Number_________________________ EXERCISE 1-1: Write a program which displays
information about you like: Your Name, Fathers Name, Class Roll No., age, and Cell Phone
number. EXERCISE 1-2: Write down a program which has 2 variable ‘a’ and ‘b’ assign them any
value and evaluate the following equation: x = a2 + 2ab + b2 Create variable x and Display the
result of ‘x’ DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING
AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS
(2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid
Javed Korai WEEK. 4 Page: 1/15 Roll Number_________________________
Name____________________________ Topic Covered : The if statement, if-else statement,
nested if , else-if structure , Random Class , switch statement, for loop , nested for loops . IF
STATEMENT Following is the syntax of if statement: if(Boolean_expression) { } If the Boolean
expression evaluates to true then the block of code inside the if statement will be executed. If not,
the first set of code after the end of the if statement (after the closing curly brace) will be executed.
IF-ELSE STATEMENT Following is the syntax of an if...else statement: if(Boolean_expression) { }
else { } If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed. PROG RAM 1 : Demonstrating basic if-else
statement. import [Link]; class PassingGrade { public static void main( String [ ] args ) {
Scanner scan = new Scanner( [Link] ); [Link]( "Enter Marks : " ); int marks =
[Link]( ); String message; if ( marks >= 60 ) message = "You passed"; else message = "You
failed "; [Link]( message ) ; } } DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 4 Page: 2/15 Roll
Number_________________________ Name____________________________ NESTED IF AND
ELSE -IF STRUCTURE It is always legal to nest if- else statements which means you can use one
if or else if statement inside another if or else if statement. The syntax for a nested if is as follows:
if(Boolean_expression 1) { if(Boolean_expression 2) { } } You can nest else if...else in the similar
way as we have nested if statement: if(Boolean_expression 1) { } else if(Boolean_expression 2) { }
else { } PROGRAM 2: Demonstrating if -else-if statements. import [Link]; class
LetterGrade { public static void main( String [] args ) { Scanner scan = new Scanner( [Link] );
char grade; [Link]( "Enter your test grade: " ); int score = [Link]( ); if ( score >= 90 )
grade = 'A'; else if ( score >= 80 ) grade = 'B'; else if ( score >= 70 ) grade = 'C'; else if ( score >= 60
) grade = 'D'; else grade = 'F'; [Link]("Your test score "+score+" has "+grade+" Grade"
); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 4 Page: 3/15 Roll Number_________________________
Name____________________________ PROGRAM 3 : Demonstrating if-else-if statements. class
IfElse { public static void main(String args[]) { int month = 4; String season; if(month == 12 || month
== 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season =
"Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 ||
month == 10 || month == 11) season = "Autumn"; else season = "Bogus Month";
[Link]("April is in the " + season + "."); } } GENERATING RANDOM NU MBERS WITH
TH E RANDOM CLASS The Random class, which is in the [Link] package, uses a mathematical
formula to generate a sequence of numbers, feeding the formula a seed value, which determines
where in that sequence the set of random numbers will begin . PROGRAM 4 : Demonstrating
if-else-if statements and Random class . DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 4 Page: 4/15 Roll
Number_________________________ Name____________________________ import
[Link]; import [Link]; class GuessANumber { public static void main( String [ ]
args ) { Random random = new Random( ); int secretNumber = [Link]( 10 ) + 1; Scanner
scan = new Scanner( [Link] ); [Link]( "I'm thinking of a number" + " between 1 and
10. What is your guess? " ); int guess = [Link]( ); if ( guess < 1 || guess > 10 ) {
[Link]( "Well, if you're not going to try," + " I'm not playing." ); } else { if ( guess ==
secretNumber ) [Link]( "Hoorah. You win!" ); else { [Link]( "The number
was " + secretNumber ); if ( [Link]( guess - secretNumber ) > 3 ) [Link]( "You
missed it by a mile!" ); else [Link]( "You were close." ); [Link]( "Better luck
next time." ); } } } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 4 Page: 5/15 Roll Number_________________________
Name____________________________ SWITCH STATEMENT A switch statement allows a
variable to be tested for equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each case. switch(expression) { case value : break; case
value : break; default : } The following rules apply to a switch statement: • The variable us ed in a
switch statement can only be integers, convertible integers (byte, short, char), strings and enums.
Beginning with JDK 7, you can use a string to control a switch statement. • You can have any
number of case statements within a switch. Each case is f ollowed by the value to be compared to
and a colon. • The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal. • When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is reached. • When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line following
the switch statement. • Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached. • A switch statement can have
an optional default case, which must appear at the end of the switch. The default case can be used
for performing a task when none of the cases is true. No break is needed in the default case. • You
can use a switch as part of the statement sequence of an outer switch. This is called a nested
switch. DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 4 Page: 6/15 Roll Number_________________________
Name____________________________ PROGRAM 5 : Demonstrating simple switch. class
SampleSwitch { public static void main(String args[]) { int i = 3; switch(i) { case 0:
[Link]("i is zero."); break; case 1: [Link]("i is one."); break; case 2:
[Link]("i is two."); break; case 3: [Link]("i is three."); break; default:
[Link]("i is greater than 3."); } } } PROGRAM 6 : Demonstrating that in a switch, break
statements are optional. class MissingBreak { public static void main(String args[]) { int i = 6;
switch(i) { case 0: case 1: case 2: case 3: case 4: [Link]("i is less than 5"); break; case
5: case 6: case 7: case 8: case 9: [Link]("i is less than 10"); break; default:
[Link]("i is 10 or more"); DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 4 Page: 7/15 Roll
Number_________________________ Name____________________________ } } } PROGRAM
7 : Demonstrating switch class Switch { public static void main(String args[]) { int month = 4; String
season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5:
season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10:
case 11: season = "Autumn"; break; default: season = "Bogus Month"; } [Link]("April is
in the " + season + "."); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 4 Page: 8/15 Roll Number_________________________
Name____________________________ FOR LOOP AND NESTED FOR LOOP S A for loop is a
repetition control structure that allows you to efficiently write a loop that needs to be executed a
specific number of times. A for loop is useful when you know how many times a task is to be
repeated. The syntax of a for loop is : for(initialization; Boolean_expression; update) { } Here is the
flow of control in a for loop: • The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables and this step ends with a semi colon (;). •
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop will not be executed and control jumps to the next statement past the for loop. •
After the body of the for loop gets executed, the control jumps back up to the update statement.
This statement a llows you to update any loop control variables. This statement can be left blank
with a semicolon at the end. • The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then Bool ean expression). After
the Boolean expression is false, the for loop terminates. PROGRAM 8 : Demo nstrate the for loop.
class ForTick { public static void main(String args[]) { int n; for(n=10; n>0; n--)
[Link]("tick " + n); } } PROGRAM 9 : Declare a loop control variable inside the for. class
ForTick { public static void main(String args[]) { for(int n=10; n>0; n--) [Link]("tick " + n);
} } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 4 Page: 9/15 Roll Number_________________________
Name____________________________ PROGRAM 1 0: Using the comma in for loop class
Comma { public static void main(String args[]) { int a, b; for(a=1, b=4; a colorBox = new
JComboBox<>(colors); [Link](okButton); [Link](nameLabel); [Link](nameField);
[Link](boldCheck); [Link](redRadio); [Link](blueRadio); [Link](colorBox);
[Link](500, 150); [Link](JFrame.EXIT_ON_CLOSE);
[Link](null); [Link](true); } } Program 2: Demonstrate Gird Layout
& action listener to the button import [Link].*; JButton, JTextField, etc.) import [Link].*;
import [Link].*; DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 9 Page: 4/10 Roll Number_________________________
Name____________________________ public class StudentDetailsForm { public static void
main(String[] args) { starts here) JFrame frame = new JFrame("Student Details");
[Link](new GridLayout(6, 2, 5, 5)); JLabel nameLabel = new JLabel("Student Name:");
JTextField nameField = new JTextField(); JTextField rollField = new JTextField(); JLabel
courseLabel = new JLabel("Course:"); JTextField courseField = new JTextField(); JLabel
genderLabel = new JLabel("Gender:"); JRadioButton male = new JRadioButton("Male");
ButtonGroup genderGroup = new ButtonGroup(); [Link](male);
[Link](female); DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 9 Page: 5/10 Roll Number_________________________
Name____________________________ [Link](male); [Link](female); public
void actionPerformed(ActionEvent e) { String roll = [Link](); String course =
[Link](); [Link]() ? "Female" : "Not Selected";
[Link](frame, "Student Details:\n" + "Name: " + name + "\n" + "Roll
Number: " + roll + "\n" + "Course: " + course + "\n" + "Gender: " + gender); } });
[Link](nameLabel); [Link](rollLabel); [Link](rollField); [Link](courseLabel);
[Link](courseField); DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 9 Page: 6/10 Roll Number_________________________
Name____________________________ [Link](genderPanel); [Link](new JLabel());
[Link](showBtn); [Link](400, 250);
[Link](JFrame.EXIT_ON_CLOSE); [Link](null);
[Link](true); DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 9 Page: 7/10 Roll Number_________________________
Name____________________________ Program 3: Demonstration of Menu- Driven Application
Using Java JOptionPane with Calculator and Other Options import [Link]; class
MainMenu { int option; public void mainMenu() { do { option =
[Link]([Link]( "SELECT FROM THIS MENU" + " \n1. Calculator"
+ " \n2. Converter" + " \n3. Marksheet" + " \n4. Exit" + " \nEnter Your Choice: " )); switch (option) {
case 1: Calculator cl = new Calculator(); [Link](); break; case 2: Converter conv = new
Converter(); [Link](); break; case 3: Marksheet ms = new Marksheet(); [Link](); break;
case 4: [Link](null, "Thank You for Using"); Exit message break;
default: [Link](null, "Invalid Option"); Invalid input } } while (option != 4);
} } class Calculator { int n1, n2, option; public void menu() { do { DEPARTMENT OF INFORMATION
TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 9 Page: 8/10 Roll
Number_________________________ Name____________________________ option =
[Link]([Link]( "Calculator Menu\ n" + "1. Add\ n2. Subtract\ n3.
Multiply\ n4. Divide\ n5. Back")); switch (option) { case 1: add(); break; case 2: sub(); break; case 3:
mul(); break; case 4: div(); break; case 5: [Link](null, "Returning to
Main Menu"); break; default: [Link](null, "Invalid Option"); } } while
(option != 5); } public void init() { n1 = [Link]([Link]("Enter 1st
Value: ")); n2 = [Link]([Link]("Enter 2nd Value: ")); } + " = " + (n1
+ n2)); } public void sub() { init(); [Link](null, n1 + " - " + n2 + " = " + (n1
- n2)); } public void mul() { init(); [Link](null, n1 + " x " + n2 + " = " + (n1
* n2)); } public void div() { init(); if (n2 == 0) [Link](null, "Cannot divide
by zero!"); else [Link](null, n1 + " / " + n2 + " = " + (n1 / n2)); } } class
Converter { int choice = [Link]([Link]( "Converter Menu\ n" + "1.
Celsius to Fahrenheit\ n" + "2. Kilometer to Miles\ n" + "3. Back\ n" + "Enter your choice: " )); switch
(choice) { case 1: celsiusToFahrenheit(); break; DEPARTMENT OF INFORMATION
TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 9 Page: 9/10 Roll
Number_________________________ Name____________________________ case 2:
kmToMiles(); break; case 3: [Link](null, "Returning to Main Menu");
break; default: [Link](null, "Invalid Option"); } } public void
celsiusToFahrenheit() { double c = [Link]([Link]("Enter
Temperature in Celsius: ")); double f = (c * 9 / 5) + 32; [Link](null, c +
"°C = " + f + "°F"); } public void kmToMiles() { double km =
[Link]([Link]("Enter Distance in Kilometers: ")); double miles
= km * 0.621371; [Link](null, km + " km = " + miles + " miles"); } }
public void menu() { String name = [Link]("Enter Student Name: "); int
math = [Link]([Link]("Enter Math Marks: ")); int sci =
[Link]([Link]("Enter Science Marks: ")); int eng =
[Link]([Link]("Enter English Marks: ")); int total = math + sci +
eng; double perc = total / 3.0; String grade; if (perc >= 75) grade = "A"; else if (perc >= 60) grade =
"B"; else if (perc >= 50) grade = "C"; else grade = "F "; String result = "Student Name: " + name + "
\nMath: " + math + " \nScience: " + sci + " \nEnglish: " + eng + " \nTotal: " + total + " \nPercentage: "
+ perc + " \nGrade: " + grade; [Link](null, result); DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 9 Page:
10/10 Roll Number_________________________ Name____________________________ } class
Test { public static void main(String[] args) { MainMenu ob = new MainMenu(); [Link](); } }
DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 8 Page: 1/14 Roll Number_________________________
Name____________________________ TOPIC S COVERED: METHOD OVERRIDING,
METHOD OVERRIDING AND DYNAMIC METHOD DISPATCH, SUPER KEYWORD IN METHOD
OVERRIDING, ABSTRACT CLASS & USING FINAL TO PREVENT INHERITANCE. METHOD
OVERRIDING Declaring a method in sub class which is already present in parent class is known as
method overriding. In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to override the
method in the superclass. When an overridden metho d is called from within its subclass, it will
always refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden. Overriding is done so that a child class can give its own
implementation t o a method which is already provided by the parent class. In this case the method
in parent class is called overridden method and the method in child class is called overriding
method. The main advantage of method overriding is that the class can give its own specific
implementation to an inherited method without even modifying the parent class code. In object
-oriented terms, overriding means to override the functionality of an existing method. This is helpful
when a class has several child classes, so if a child class needs to use the parent class method, it
can use it and the other classes that want to have different implementation can use overriding
feature to make changes without touching the parent class code. • The argument list should be
exactly the sa me as that of the overridden method. • A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re -declared. • Constructors cannot be
overridden. PROGRAM 1: Demonstrate simple method overriding class Animal { public void move()
{ [Link]("Animals can move"); } } class Dog extends Animal { public void move() {
[Link]("Dogs can walk and run"); } } public class TestDog { public static void
main(String args[]) { Animal a = new Animal(); [Link](); [Link](); } } DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 2/14
Roll Number_________________________ Name____________________________ METHOD
OVERRIDING AN D DYNAMIC METHOD DIS PATCH Method Overriding is an exa mple of runtime
polymorphism. When a parent class reference points to the child class object then the call to the
overridden method is determined at runtime, because during method call which method(parent
class or child class) is to be executed is determin ed by the type of object. This process in which call
to the overridden method is resolved at runtime is known as dynam ic method dispatch. PROGRAM
2: Demonstrate Method Overriding and Dynamic Method Dispatch class A{ public void disp() {
[Link]("disp() method of parent class"); } } class B extends A{ public void disp(){
[Link]("disp() method of Child class"); } public void newMethod(){
[Link]("new method of child class"); } } Class Demo{ public static void main( String
args[]) { A obj = new A(); [Link](); A obj2 = new B (); [Link](); } } In the above example the call
to the disp() method using second object (obj2) is runtime polymorphism (or dynamic method
dispatch). Note : In dynamic method dispatch the object can call the overriding methods of child
class and all the non-overridden methods of base class but it cannot call the methods which are
newly declared in the child class. DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY
OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE
NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24
-320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 3/14 Roll
Number_________________________ Name____________________________ In the above
example the object obj2 is calling the disp() . However if you try to call the newMethod() method
(which has been newly declared in B class) using obj2 then you would give compilation error with
the following message: [Link]: error: cannot find symbol [Link](); ^ symbol:
method newMethod () location: variable obj2 of type A SUPER KEYWORD IN MET HOD
OVERRIDING When invoking a superclass version of an overridden method the super keyword is
used. A subclass can override an inherited method by providing a new version of the method. The
new method’s name and parameters must be identical to the inherited method. To call the inherited
version of the method, the subclass uses the super object reference using the following syntax:
[Link] ( argument list ); If yo u create an object of the subclass and call the member
method which exists in both classes ( super and sub), the member method of the subclass is
invoked and the method of the subclass is ignored. class A { .. .. .. void getData() { .. .. .. } } class B
extends A { .. .. .. void getData() { .. .. .. } } class Test { public static void main(String a[] ) { B obj =
new B() ; [Link](); } } To access the overridden method of the super class from the subclass, s
uper keywor d is used. If you want to access getData() method of the super class, you can use the
‘[Link] Data()’ in the subclass. class A { .. .. .. void getData() { .. .. .. } } class B extends A { .. .. ..
void getData() { .. .. .. [Link](); .. .. .. } } class Test { public static void main(String a[] ) { B obj
= new B() ; [Link](); } } This method will be called This method will not be called Function
called 1st Function called 2nd DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 8 Page: 4/14 Roll Number_________________________
Name____________________________ PROGRAM 3: Demonstrate Method Overriding with
super keyword class Animal { public void move() { [Link]("Animals can move"); } } class
Dog extends Animal { public void move() { [Link](); [Link]("Dogs can walk and
run"); } } public class TestDog { public static void main(String args[]) { Animal b = new Dog();
[Link](); } } PROGRAM 4: Demonstrate Method Overriding with super keyword class A { int i, j;
A(int a, int b) { i = a; j = b; } void show() { [Link]("i and j: " + i + " " + j); } } class B
extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { [Link]();
[Link]("k: " + k); } } class Override { public static void main(String args[]) { B subOb =
new B(1, 2, 3); [Link](); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY
OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE
NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24
-320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 5/14 Roll
Number_________________________ Name____________________________ PROGRAM 5:
Demonstrate Method Overriding class Figure { double dim1; double dim2; Figure(double a, double
b) { dim1 = a; dim2 = b; } double area() { [Link]("Area for Figure is undefined."); return
0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); }
[Link]("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends
Figure { Triangle(double a, double b) { super(a, b); } double area() { [Link]("Inside Area
for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) {
Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8);
[Link]("Area is " + [Link]()); [Link]("Area is " + [Link]());
[Link]("Area is " + [Link]()); } } DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 6/14 Roll
Number_________________________ Name____________________________ ABSTRACT
CLASS An abstract class is a class that is not completely implemented. Usually, an abstract class
contains at least one abstract method, that is, a method that specifies an API that subclasses
should implement, but does not provide an implementation for the method. Because an abstract
class is not complete, it cannot be used to instantiate objects. An abstract class can be extended,
however, so that its subclasses can complete the implementation of the abstract methods and can
be instantiated. A class is declared to be abstract by including the abstract keyword in the class
header, as shown in the following syntax: accessModifier abstract class ClassName An abstract
method is defined by including the abstract keyword in the method header and by using a
semicolon to indicate that there is no code for the method, as shown in the following syntax:
accessModifier abstract return_type methodName (argument list); RESTRICTION FOR DEFI NING
ABSTRACT CLASS AND METHODS DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 7/14 Roll
Number_________________________ Name____________________________ PROGRAM 6 :
Demonstrates Abstract Employee class abstract class Employee { private String name; private
String address; private int number; public Employee(String name, String address, int number) {
[Link]("Constructing an Employee"); [Link] = name; [Link] = address;
[Link] = number; } abstract public double computePay(); abstract public void mailCheck();
public String toString() { return name + " " + address + " " + number; } public String getName() {
return name; } public String getAddress() { return address; } public void setAddress(String
newAddress) { address = newAddress; } public int getNumber() { return number; } } class Salary
extends Employee { private double salary; public Salary(String name, String address, int number,
double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() {
DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 8 Page: 8/14 Roll Number_________________________
Name____________________________ [Link]("Within mailCheck of Salary class ");
[Link]("Mailing check to " + getName() + " with salary " + salary); } public double
getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary
= newSalary; } } public double computePay() { [Link]("Computing salary pay for " +
getName()); return salary/52; } } public class AbstractDemo { public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new
Salary("John Adams", "Boston, MA", 2, 2400.00); [Link]("Call mailCheck using Salary
reference --"); [Link](); [Link]("\n Call mailCheck using Employee reference--");
[Link](); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 8 Page: 9/14 Roll Number_________________________
Name____________________________ USING FINAL TO PREVE NT INHERITANCE
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As
you might expect, it is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete impleme ntations. Here is an
example of a final class PROGRAM 6 : Demonstrates Final class to prevent inheritance final class
Calculator { private String model; public Calculator(String model) { [Link] = model; } public int
add(int a, int b) { return a + b; } public int multiply(int a, int b) { return a * b; } public String getModel()
{ return model; } } public class Main { public static void main(String[] args) { Calculator calc = new
Calculator("Scientific"); [Link]("Calculator Model: " + [Link]());
[Link]("5 + 3 = " + [Link](5, 3)); [Link]("5 * 3 = " + [Link](5, 3)); } }
DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 8 Page: 10/14 Roll Number_________________________
Name____________________________ Exercise 7.1 Write a Java program where a s ubclass
overrides a method from its superclass and displays different messages. DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page:
11/14 Roll Number_________________________ Name____________________________
Exercise 7.2 Write a Java program to demonstrate dynamic method dispatch using a superclass
reference that refers to subclass objects. DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page: 12/14 Roll
Number_________________________ Name____________________________ Exercise 7.3
Write a Java program that uses the `super` keyword to call the superclass version of an overridden
method. DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 8 Page: 13/14 Roll Number_________________________
Name____________________________ Exercise 7.4 Write a Java program that defines an
abstract class with one abstract method and a subclass that implements it. DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 8 Page:
14/14 Roll Number_________________________ Name____________________________
Exercise 7.5 Write a Java program that demonstrates how the “ final” keyword prevents a class
from being inherited. DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 7 Page: 1/13 Roll Number_________________________
Name____________________________ Topic Covered : Inheritance in Java, super class,
subclass, extends keyword and the super Keyword . Types of Inheritance, multilevel Inheritance
INHERITANCE IN JAVA • Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. • This also provides an opportunity to reuse
the code functionality and fast implementation time. When creating a class, instead of writing
completely new data members and member methods, the programmer can designate that the new
class should inherit the mem bers of an existing class. • The idea of inheritance implements the “is
a” relationship. For example, mammal IS -A animal, dog IS -A mammal hence dog IS -A animal as
well and so on. • Inheritance lets us organize related classes into ordered levels of functional ity,
called hierarchies. The advantage is that we write the common code only once and reuse it in
multiple classes. • A subclass inherits methods and fields of its superclass. A subclass can have
only one direct superclass, but many subclasses can in herit from a common superclass. •
Inheritance implements the “is a” relationship between classes. Any object of a subclass is also an
object of the superclass. • All classes inherit from the Object class. • To specify that a subclass
inherits from a superclass, the su bclass uses the extends keyword in the class definition, as in the
following syntax: AccessModifier class CassName extends SuperClassName • A subclass does not
inherit constructors or private members of the superclass. However, the superclass constructors ar
e still available to be called from the subclass, and the private fields of the superclass are
implemented as fields of the subclass. • To access private fields of the superclass, the subclass
needs to use the methods provided by the superclass. • To call th e constructor of the superclass,
the subclass constructor uses the following syntax: super ( argument list ); • If used, this statement
must be the first statement in the subclass constructor. • A subclass can override an inherited
method by providing a new v ersion of the method. The new method’s API must be identical to the
inherited method. To call the inherited version of the method, the subclass uses the super object
reference using the following syntax: [Link] ( argument list ); • Any field declared
using the protected access modifier is inherited by the subclass. As such, the subclass can directly
access the field without calling its method. DEPARTMENT OF INFORMATION TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page: 2/13 Roll
Number_________________________ Name____________________________ • In M ultilevel
Inheritance, a sub class will be inheriting a super class and as well as the subclass als o act as the
super class to other class. In below image, the class A serves as a super class for the subclass B,
which in turn serves as a superc lass for the sub class C. PROGRAM 1: A simple example of
inheritance. class A { int i, j; A() { i = 100; j = 200; } void showij() { [Link]("i and j: " + i + "
" + j); } } class B extends A { int k; B() { k = 300; } void showk() { [Link]("k: " + k); } void
sum() { [Link]("i+j+k: " + (i + j + k)); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page: 3/13 Roll
Number_________________________ Name____________________________ class Test {
public static void main(String args[]) { B ob = new B(); [Link](); [Link](); [Link](); } }
PROGRAM 2: This progra m uses inheritance to extend A class A { int i, j; A() { i = 100; j = 200; } int
sumIJ() { return i + j; } } class B extends A { int k; B() { k = 300; } int getK() { return k; } int sumAll() {
return i + j + k; } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 7 Page: 4/13 Roll Number_________________________
Name____________________________ class Test { public static void main(String[] args) { B ob =
new B(); int sumIJ = [Link](); [Link]("Sum of i and j: " + sumIJ); int kValue =
[Link](); [Link]("Value of k: " + kValue); int total = [Link]();
[Link]("Sum of i, j, and k: " + total); } } PROGRAM 3: This program uses a super
keyword class BankAccount { private String accountNumber; private double balance;
BankAccount(String accountNumber, double balance) { [Link] = accountNumber;
[Link] = balance; } String getAccountNumber() { return accountNumber; } double
getBalance() { return balance; } } class SavingsAccount extends BankAccount { private double
interestRate; DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF ENGINEERING
AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS
(2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid
Javed Korai WEEK. 7 Page: 5/13 Roll Number_________________________
Name____________________________ accountNumber and balance SavingsAccount(String
accountNumber, double balance, double interestRate) { super(accountNumber, balance);
[Link] = interestRate; } void displayAccountDetails() { [Link]("Account
Number: " + [Link]()); [Link]("Balance: " + [Link]());
[Link]("Interest Rate: " + interestRate + "%"); } } class Test { public static void
main(String[] args) { SavingsAccount sa = new SavingsAccount("ACC123", 5000.0, 5.0);
[Link](); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 7 Page: 6/13 Roll Number_________________________
Name____________________________ LEVELS OF INHERITANC E DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page: 7/13
Roll Number_________________________ Name____________________________ PROGRAM
4 : Demonstrate Multi -level inheritance brand = ""; } void showBrand() { [Link]("Brand:
" + brand); } } int speed; Car() { speed = 0; } void showSpeed() { [Link]("Speed: " +
speed + " km/h"); } } class ElectricCar extends Car { int batteryCapacity; ElectricCar() {
batteryCapacity = 0; } kWh"); } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 7 Page: 8/13 Roll Number_________________________
Name____________________________ } class Test { public static void main(String[] args) {
ElectricCar ec = new ElectricCar(); [Link] = "Tesla"; [Link] = 250; [Link] = 100;
[Link](); [Link](); } PROGRAM 4 : Demonstrate hierarchical inheritance .
class Vehicle { String brand; Vehicle(String brand) { [Link] = brand; } [Link]("Brand:
" + brand); } } [Link] = speed; } DEPARTMENT OF INFORMATION TECHNOLOGY FACULTY
OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE
NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24
-320/321) Instructor: Junaid Javed Korai WEEK. 7 Page: 9/13 Roll
Number_________________________ Name____________________________
[Link]("Car speed: " + speed + " km/h"); } } class Bike extends Vehicle { boolean
hasCarrier; [Link] = hasCarrier; } void showCarrier() { [Link]("Has carrier: " +
hasCarrier); } } public static void main(String[] args) { Car car = new Car("Toyota", 180); Bike bike =
new Bike("Honda", true); [Link](); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page: 10/13 Roll
Number_________________________ Name____________________________ Exercise 7.1
Write a Program which Demonstr ates Super keyword using private member DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page:
11/13 Roll Number_________________________ Name____________________________
Exercise 7.2 Write a Program which Demonstrates Single inheritance DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page:
12/13 Roll Number_________________________ Name____________________________
Exercise 7. 3 Write a Program, which Demonstrates multilevel inheritance DEPARTMENT OF
INFORMATION TECHNOLOGY FACULTY OF ENGINEERING AND TECHNOLOGY UNIVERSITY
OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT
ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 7 Page:
13/13 Roll Number_________________________ Name____________________________
Exercise 7. 4 Write a P rogram , which Demonstrates hierarchical inheritance DEPARTMENT OF
INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY
UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025
OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6
Page: 1/34 Roll Number_________________________ Name____________________________
Topic Covered : OOP principles , Abstraction, Encapsulation , Inheritance , Polymorphism , Method
Overloading , Method Overriding, Constructor Overloading . OOP PRINCIPLES ABSTRACTION
Abstraction in Java is a core principle of Object -Oriented Programming (OOP) that focuses on
hiding implementation details and showing only essential features to the user. It simplifies complex
systems by presenting a high -level view and allowing users to interact with objects without needing
to understand their internal work ings. Key concepts of Abstraction in Java: Hiding Complexity:
Abstraction reduces complexity by concealing the intricate details of how a feature is implemented.
Users interact with a simplified interface, focusing on what an object does rather than how it does it.
Achieved through Abstract Classes and Interfaces: • Abstract Classes: These classes are declared
with the abstract keyword and may or may not contain abstract methods. They cannot be
instantiated directly, and subclasses must implement their abstract methods or declare themselves
abstract. Abstract classes can also contain concrete methods and fields. • Interfaces: Interfaces are
blueprints for classes, containing only abstract methods (implicitly public and abstract) and
static/default methods (from Java 8 onwards). Classes that implement an interface must provide
implementations for all its abstract methods. Interfaces enable multiple inheritance of type in Java.
Focus on Functionality: Abstraction emphasizes the functionality or behavior of an object, providing
a contract for how it can be used, while leaving the specific implementation details to be handled by
concrete subclasses or implementing classes. DEPARTMENT OF INFORMATION TECHNOLOGY
FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 2/34 Roll
Number_________________________ Name____________________________
ENCAPSULATION Encapsulation is all about wrapping variables and methods in one single unit.
Encapsulation is also known as data hiding. When you design your class you may (and you should)
make your variables hidden from other classes and provide methods to manipulate the data
instead. To achieve encapsulation in Java: • Declare the variables of a class as private. • Provide
public setter and getter methods to modify and view the variables values. INHERITANCE
Inheritance is the OOP ability that allows Java classes to be derived from other classes. It transfers
the characteristic s of a class to other classes that are derived from it. The parent class is called a
superclass and the derivatives are called subclasses. Subclasses inherit fields and methods from
their superclasses. DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 3/34 Roll Number_________________________
Name____________________________ POLYMORPHISM The word polymorphism means
having many forms. In simple words, we can define polymorphism as the ability of a message to be
displayed in more than one form. Polymorphism is considered as one of the important features of
Object Oriented Programming. Polymorphism allows us to perform a single action in different ways.
In other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So it means many
forms. In Java polymorphism is mainly divided into t wo types: • Compile time polymorphism: It is
also known as static polymorphism. This type of polymorphism is achieved by function overloading
or operator overloading. • Runtime polymorphism: It is also known as Dynamic Method Dispatch. It
is a process in which a function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. METHOD O VERLOADING Method Overloading
is a feature that allows a class to have more than one method having the same name, if t heir
argument lists are different. A rgument list it means the parameters that a method has: For example
the argument list of a method add(int a, int b) having two parameters is different from the argument
list of the method add(int a, int b, int c) having three parameters. In order to overload a method, the
argument lists of the methods must differ in either of these: 1. Number of parameters. For example:
add(int, int) add(int, int, int) 2. Data type of parameters. For example: add(int, int) add(int, float) 3.
Sequence of Data type of parameters. For example: add(int, float) add(float, int) DEPARTMENT OF
INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY
UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025
OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6
Page: 4/34 Roll Number_________________________ Name____________________________
PROGRAM 1: Demonstrate Abstraction using abstract. To run Program save this file “[Link]”
abstract class Animal { abstract void makeSound(); } class Dog extends Animal {
[Link]("Woof! Woof!"); } } public class Main { public static void main(String[] args) {
Animal myDog = new Dog(); [Link](); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 5/34 Roll
Number_________________________ Name____________________________ PROGRAM 2 :
Demonstrate Abstraction using Interface. To run Program save this file “Main .java ” interface
Animal { void makeSound(); [Link]("Woof! Woof!"); } } public class Main { public static
void main(String[] args) { interface Animal myDog = new Dog(); [Link](); } }
DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 6 Page: 6/34 Roll Number_________________________
Name____________________________ PROGRAM 3: Demonstrate Encapsulation. To run
Program save this file “[Link]” class Person { class private String name; } public String
getName() { return name; } } public class Main { public static void main(String[] args) { Person p =
new Person(); 'name' is private [Link]("Alice"); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 7/34 Roll
Number_________________________ Name____________________________ PROGRAM 4:
Demonstrate Inheritance. To run Program save this file “[Link]” class Animal { void eat() {
[Link]("Animal eats food"); } } class Dog extends Animal { } } public class Main { public
static void main(String[] args) { Dog d = new Dog(); [Link](); [Link](); } } DEPARTMENT OF
INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY
UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025
OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6
Page: 8/34 Roll Number_________________________ Name____________________________
PROGRAM 5: Demonstrate method overloading. To run Program save this file “Overload .java ”
class OverloadDemo { void test() { [Link]("No parameters"); } void test(int a) {
[Link]("a: " + a); } void test(int a, int b) { [Link]("a and b: " + a + " " + b); }
double test(double a) { [Link]("double a: " + a); return a * a; } } class Overload { public
static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; [Link]();
[Link](10); [Link](10, 20); result = [Link](123.25); [Link]("Result of [Link](123.25): "
+ result); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING
AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS
(2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid
Javed Korai WEEK. 6 Page: 9/34 Roll Number_________________________
Name____________________________ INVALID CASE OF METH OD OVERLOADING: If two
methods have same name, same parameters and have different return type, then this is not a valid
method - overloading example. This will throw compilation error. int add(int, int) float add(int, int)
AUTOMATIC TYPE CONVE RSION IN OVERLOADING When an overloaded method is called,
Java looks for a match between the arguments used to call the method and the method’s
parameters. However, this match need not alway s be exact. In some cases, Java’s automatic type
conversions can play a role in overload resolution. DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 10/34 Roll
Number_________________________ Name____________________________ PROGRAM 6 :
Demonstrate method overriding . To run Program save this file “Main .java ” class Person { void
role() { [Link]("I am a person."); } } class Father extends Person { void role() {
[Link]("I am a father."); } } class Employee extends Person { void role() {
[Link]("I am an employee."); } } class Husband extends Person { void role() {
[Link]("I am a husband."); } } public class Main { public static void main(String[] args) {
Person p1 = new Father(); Person p2 = new Employee(); Person p3 = new Husband(); [Link]();
[Link](); [Link](); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 11/34 Roll Number_________________________
Name____________________________ PROGRAM 7 : Automatic type conversions apply to
overloading. Save this file “Overload .java” class OverloadDemo { void test() {
[Link]("No parameters"); } void test(int a, int b) { [Link]("a and b: " + a + " "
+ b); } void test(double a) { [Link]("Inside test(double) a: " + a); } } class Overload {
public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88;
[Link](); [Link](10, 20); [Link](i); [Link](123.2); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 12/34 Roll
Number_________________________ Name____________________________
CONSTRUCTOR OVERLOAD ING Constructor overloading is a concept of having more than one
constructor with different parameters list, in such a way so that each constructor performs a
different task. PROGRAM 8 : Constr uctor Overloading class Box { double width; double height;
double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width =
- 1; height = - 1; depth = - 1; } Box(double len) { width = height = depth = len; } double volume() {
return width * height * depth; } } class OverloadCons { public static void main(String args[]) { Box
mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7);
DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 6 Page: 13/34 Roll Number_________________________
Name____________________________ double vol; vol = [Link]();
[Link]("Volume of mybox1 is " + vol); vol = [Link]();
[Link]("Volume of mybox2 is " + vol); vol = [Link]();
[Link]("Volume of mycube is " + vol); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 14/34 Roll
Number_________________________ Name____________________________ Exercise 6 -1:
Abstraction Create an abstract class shape with an abstract method area(). Create subclasses
circle and rectangle. Implement the area() method in each subclass. Test by creating objects and
printing their areas. DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 15/34 Roll Number_________________________
Name____________________________ Exercise 6 -1: Encapsulation Create a class Student with
private variables name and age. Add getters and setters. Validate age so it cannot be negative.
Test by setting values and printing them. DEPARTMENT OF INFORMATION TECHNOLOGY
FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 16/34 Roll
Number_________________________ Name____________________________ Exercise 6 -1:
Inheritance Create a parent class Vehicle with a method start(). Create a child class Car that
inherits from Vehicle and adds a method fuelType(). Test by creating a Car object and calling both
methods. DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 6 Page: 17/34 Roll Number_________________________
Name____________________________ Topic Covered : OOP principles , Abstraction,
Encapsulation , Inheritance , Polymorph ism, Method Overloading , Method Overriding, Constructor
Overloading . OOP PRINCIPLES ABSTRACTION Abstraction in Java is a core principle of Object
-Oriented Programming (OOP) that focuses on hiding implementation details and showing only
essential features to the user. It simplifies complex systems by presenting a high -level view and
allowing users to interact with objects without needing to understand their internal workings. Key
concepts of Abstraction in Java: Hiding Complexity: Abstraction reduc es complexity by concealing
the intricate details of how a feature is implemented. Users interact with a simplified interface,
focusing on what an object does rather than how it does it. Achieved through Abstract Classes and
Interfaces: • Abstract Classes: These classes are declared with the abstract keyword and may or
may not contain abstract methods. They cannot be instantiated directly, and subclasses must
implement their abstract methods or declare themselves abstract. Abstract classes can also contain
concrete methods and fields. • Interfaces: Interfaces are blueprints for classes, containing only
abstract methods (implicitly public and abstract) and static/default methods (from Java 8 onwards).
Classes that implement an interface must provide implement ations for all its abstract methods.
Interfaces enable multiple inheritance of type in Java. Focus on Functionality: Abstraction
emphasizes the functionality or behavior of an object, providing a contract for how it can be used,
while leaving the specifi c implementation details to be handled by concrete subclasses or
implementing classes. DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 18/34 Roll Number_________________________
Name____________________________ ENCAPSULATION Encapsulation is all about wrapping
variables and methods in one single unit. Encapsulation is also known as data hiding. When you
design your class y ou may (and you should) make your variables hidden from other classes and
provide methods to manipulate the data instead. To achieve encapsulation in Java: • Declare the
variables of a class as private. • Provide public setter and getter methods to modify and view the
variables values. INHERITANCE Inheritance is the OOP ability that allows Java classes to be
derived from other classes. It transfers the characteristics of a class to other classes that are
derived from it. The parent class is called a superclass and the derivatives are called subclasses.
Subclasses inherit fields and methods from their superclasses. DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 19/34 Roll
Number_________________________ Name____________________________
POLYMORPHISM The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form.
Polymorphism is considered as one of the important features of Object Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to defin e one interface and have multiple implementations. The word “poly” means
many and “morphs” means forms, So it means many forms. In Java polymorphism is mainly divided
into two types: • Compile time polymorphism: It is also known as static polymorphism. This type of
polymorphism is achieved by function overloading or operator overloading. • Runtime
polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call
to the overridden method is resolved at Runtime. This type of poly morphism is achieved by Method
Overriding. METHOD O VERLOADING Method Overloading is a feature that allows a class to have
more than one method having the same name, if their argument lists are different. A rgument list it
means the parameters that a method has: For example the argument list of a method add(int a, int
b) having two parameters is different from the argument list of the method add(int a, int b, int c)
having three parameters. In order to overload a method, the argument lists of the methods must
differ in either of these: 1. Number of parameters. For example: add(int, int) add(int, int, int) 2. Data
type of parameters. For example: add(int, int) add(int, float) 3. Sequence of Data type of
parameters. For example: add(int, float) add(float, int) DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 20/34 Roll
Number_________________________ Name____________________________ PROGRAM 1:
Demonstrate Abstraction using abstract. To run Program save this file “[Link]” abstract class
Animal { abstract void makeSound(); } class Dog extends Animal { void makeSound() {
[Link]("Woof! Woof!"); } } public class Main { public static void main(String[] args) {
Animal myDog = new Dog(); [Link](); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 21/34 Roll
Number_________________________ Name____________________________ PROGRAM 2 :
Demonstrate Abstraction using Inte rface. To run Program save this file “[Link]” interface
Animal { void makeSound(); [Link]("Woof! Woof!"); } } public class Main { public static
void main(String[] args) { interface Animal myDog = new Dog(); [Link](); } }
DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 6 Page: 22/34 Roll Number_________________________
Name____________________________ PROGRAM 3: Demonstrate Encapsulation. To run
Program save this file “[Link]” class Person { class private String name; } public String
getName() { return name; } } public class Main { public static void main(String[] args) { Person p =
new Person(); 'name' is private [Link]("Alice"); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 23/34 Roll
Number_________________________ Name____________________________ PROGRAM 4:
Demonstrate Inheritance. To run Program save this file “[Link]” class Animal { void eat() {
[Link]("Animal eats food"); } } class Dog extends Animal { } } public class Main { public
static void main(String[] args) { Dog d = new Dog(); [Link](); [Link](); } } DEPARTMENT OF
INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY
UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025
OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6
Page: 24/34 Roll Number_________________________ Name____________________________
PROGRAM 5 : Demonstrate method overloading. To run Program save this file “Overload .java ”
class OverloadDemo { void test() { [Link]("No parameters"); } void test(int a) {
[Link]("a: " + a); } void test(int a, int b) { [Link]("a and b: " + a + " " + b); }
double test(double a) { [Link]("double a: " + a); return a * a; } } class Overload { public
static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; [Link]();
[Link](10); [Link](10, 20); result = [Link](123.25); [Link]("Result of [Link](123.25): "
+ result); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING
AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS
(2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid
Javed Korai WEEK. 6 Page: 25/34 Roll Number_________________________
Name____________________________ INVALID CASE OF METH OD OVERLOADING: If two
methods have same name, same parameters and have different return type, then this is not a valid
method - overloading example. This will throw compilation error. int add(int, int) float add(int, int)
AUTOMATIC TYPE CONVE RSION IN OVERLOADING When an overloaded method is called,
Java looks for a match between the arguments used to call the method and the method’s
parameters. However, this match need not alway s be exact. In some cases, Java’s automatic type
conversions can play a role in overload resolution. DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 26/34 Roll
Number_________________________ Name____________________________ PROGRAM 6 :
Demonstrate method overriding . To run Program save this file “Main .java ” class Person { void
role() { [Link]("I am a person."); } } class Father extends Person { void role() {
[Link]("I am a father."); } } class Employee extends Person { void role() {
[Link]("I am an employee."); } } class Husband extends Person { void role() {
[Link]("I am a husband."); } } public class Main { public static void main(String[] args) {
Person p1 = new Father(); Person p2 = new Employee(); Person p3 = new Husband(); [Link]();
[Link](); [Link](); } } DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 27/34 Roll Number_________________________
Name____________________________ PROGRAM 7 : Automatic type conversions apply to
overloading. Save this file “Overload .java” class OverloadDemo { void test() {
[Link]("No parameters"); } void test(int a, int b) { [Link]("a and b: " + a + " "
+ b); } void test(double a) { [Link]("Inside test(double) a: " + a); } } class Overload {
public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88;
[Link](); [Link](10, 20); [Link](i); [Link](123.2); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 28/34 Roll
Number_________________________ Name____________________________
CONSTRUCTOR OVERLOAD ING Constructor overloading is a concept of having more than one
constructor with different parameters list, in such a way so that each constructor performs a
different task. PROGRAM 8 : Constr uctor Overloading class Box { double width; double height;
double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width =
- 1; height = - 1; depth = - 1; } Box(double len) { width = height = depth = len; } double volume() {
return width * height * depth; } } class OverloadCons { public static void main(String args[]) { Box
mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7);
DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING AND
TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd
Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed
Korai WEEK. 6 Page: 29/34 Roll Number_________________________
Name____________________________ double vol; vol = [Link]();
[Link]("Volume of mybox1 is " + vol); vol = [Link]();
[Link]("Volume of mybox2 is " + vol); vol = [Link]();
[Link]("Volume of mycube is " + vol); } } DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 30/34 Roll
Number_________________________ Name____________________________ Exercise 6 -1:
Abstraction Create an abstract class shape with an abstract method area(). Create subclasses
circle and rectangle. Implement the area() method in each subclass. Test by creating objects and
printing their areas. DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF
ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/
LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321)
Instructor: Junaid Javed Korai WEEK. 6 Page: 31/34 Roll Number_________________________
Name____________________________ Exercise 6 -2: Encapsulation Create a class Student with
private variables name and age. Add getters and setters. Validate age so it cannot be negative.
Test by setting values and printing them. DEPARTMENT OF INFORMATION TECHNOLOGY
FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO
LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 32/34 Roll
Number_________________________ Name____________________________ Exercise 6 -3:
Inheritance Create a parent class Vehicle with a method start(). Create a child class Car that
inherits from Vehicle and adds a method fuelType(). Test by creating a Car object and calling both
methods . DEPARTMENT OF INFORMATION TECHNOLOGY FACULT Y OF ENGINEERING
AND TECHNOLOGY UNIVERSITY OF SINDH, JAMSHORO LECTURE NOTES/ LAB HANDOUTS
(2nd Semester) 2025 OBJECT ORIENTED PROGRAMMING (DS24 -320/321) Instructor: Junaid
Javed Korai WEEK. 6 Page: 33/34 Roll Number_________________________
Name____________________________ Exercise 6 -4: Polymorphism Method Over loading
(Compile -Time Polymorphism) Create a class Calculator with overloaded methods add() to: Add
two integers Add three integers Add two doubles DEPARTMENT OF INFORMATION
TECHNOLOGY FACULT Y OF ENGINEERING AND TECHNOLOGY UNIVERSITY OF SINDH,
JAMSHORO LECTURE NOTES/ LAB HANDOUTS (2nd Semester) 2025 OBJECT ORIENTED
PROGRAMMING (DS24 -320/321) Instructor: Junaid Javed Korai WEEK. 6 Page: 34/34 Roll
Number_________________________ Name____________________________ Exercise 6 -5:
Polymorphism Method Overriding (Ru ntime Polymorphism) Create a base class Employee with a
method work(). Subclasses: Manager, Developer Override work() in each subclass. Use a base
class reference to call overridden methods.

You might also like