0% found this document useful (0 votes)
4 views60 pages

OOPJ(java) Unit-III

The document covers Unit-III of a programming course, focusing on Arrays, Inheritance, and Interfaces in Java. It includes topics such as array declaration, operations, dynamic sizing, sorting algorithms, and inheritance principles. Each section provides definitions, advantages, disadvantages, and example code to illustrate the concepts discussed.
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)
4 views60 pages

OOPJ(java) Unit-III

The document covers Unit-III of a programming course, focusing on Arrays, Inheritance, and Interfaces in Java. It includes topics such as array declaration, operations, dynamic sizing, sorting algorithms, and inheritance principles. Each section provides definitions, advantages, disadvantages, and example code to illustrate the concepts discussed.
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/ 60

Unit-III Arrays , Inheritance , Interfaces

S.No Name of the Topic Page No Date


Chapter I Arrays
3.1 Introduction, Declaration and Initialization of Arrays 2
3.2 Storage of Array in Computer Memory, Accessing Elements of Arrays 3
3.3 Operations on Array Elements 4-5
3.4 Assigning Array to Another Array 6
3.5 Dynamic Change of Array Size 7
3.6 Sorting of Arrays, Search for Values in Arrays 8-16
3.7 Class Arrays 17-18
3.8 Two-dimensional Arrays 19
3.9 Arrays of Varying Lengths 20-21
3.10 Three-dimensional Arrays 22-24
3.11 Arrays as Vectors 25
Chapter II Inheritance
3.12 Introduction, Process of Inheritance 26
3.13 Types of Inheritances 27-33
3.14 Universal Super Class-Object Class 34-39
3.15 Inhibiting Inheritance of Class Using Final 40
3.16 Access Control and Inheritance unit-II 2.4
2.5

3.17 Multilevel Inheritance 28-29


3.18 Application of Keyword Super 40-43
3.19 Constructor Method and Inheritance 44
3.20 Method Overriding Unit-II 2.19

3.21 Dynamic Method Dispatch 45-47


3.22 Abstract Classes 48-49
3.23 Interfaces and Inheritance 31-32
Chapter III Interfaces
3.24 Introduction, Declaration of Interface 50
3.25 Implementation of Interface 51
3.26 Multiple Interfaces 52-53
3.27 Nested Interfaces 54
2.28 Inheritance of Interfaces 55
2.29 Default Methods in Interfaces 56
3.30 Static Methods in Interface 57
3.31 Functional Interfaces 58
3.32 Annotations 59-60
3.1 Introduction, Declaration and Initialization of Arrays
Definition:
 An array is a collection of similar type of elements which has contiguous memory locations.
 Java array is an object which contains elements of a similar data type.
 Additionally, The elements of an array are stored in a contiguous memory location.
 It is a data structure where we store similar elements.
 We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on

Advantages:
 Code Optimization: It makes the code optimized, we can get values or sort the data efficiently.
 Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime..
b) Array Declaration Syntax :
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Array Declaration Initialization:
int arr[] = {10,20,30,40,50}; //declaration, instantiation and initialization
String args[] = {"ram","shyam","raj"};

Object Oriented Programming Through Java Page 2


3.2 Storage of Array in Computer Memory , Accessing Elements of Arrays
a) Storage of Array in Computer Memory
 As discussed, the reference types in Java are stored in heap area. Since arrays are reference types (we
can create them using the new keyword) these are also stored in heap area.
 You can define arrays of different data types, such as byte arrays, short arrays and integer arrays.
 Since each data type uses a different number bytes to store their values, accordingly:
Example:
 A byte (typed) array uses 1 byte to store each of its array element
 A short (typed) array uses 2 bytes to store each of its array element
 A int (typed) array uses 4 bytes to store each of its array element

 This is how a byte typed array is stored in memory:


 Each array element is stored in 1 byte of memory
 The array elements are stored in contiguous memory
b) Accessing Elements of Arrays
using index
We can access an array element by referring to its index number. The indexes in arrays start with 0, meaning
that the first element has index 0, and the second has index 1 etc .

arr[0] //gives = 10;


arr[1] // gives = 20;
arr[2] // gives = 30;
arr[3] // gives = 40;
arr[4] // gives = 50;

using for-each loop


for(int i: arr)
{
System.out.print(i+" “);
}
Output: 10 20 30 40 50

Object Oriented Programming Through Java Page 3


3.3 Operations on Array Elements
 This Java program performs the Arithmetic Operations such as Addition, Subtraction, Multiplication,
and Division using those two arrays.
Example:
import java.util.Scanner;
public class ArrayArithmeticOpert1
{
private static Scanner sc;
public static void main(String[] args)
{
int Size, i;
sc = new Scanner(System.in);

System.out.print(" Please Enter Number of elements in an array : ");


Size = sc.nextInt();

int [] a = new int[Size];


int [] b = new int[Size];
int [] Addition = new int[Size];
int [] Subtraction = new int[Size];
int [] Multiplication = new int[Size];
int [] Division = new int[Size];
float [] Module = new float[Size];
System.out.print(" Please Enter " + Size + " elements of an Array : ");
for (i = 0; i < Size; i++)
{
a[i] = sc.nextInt();
}

System.out.print(" Please Enter " + Size + " elements of an Array : ");


for (i = 0; i < Size; i++)
{
b[i] = sc.nextInt();
}

for(i = 0; i < Size; i ++)


{
Addition [i] = a[i] + b[i];
Subtraction [i]= a[i] - b[i];
Multiplication [i]= a[i] * b[i];
Division [i] = a[i] / b[i];
Module [i] = a[i] % b[i];
}

Object Oriented Programming Through Java Page 4


System.out.println("\n Add \t Sub \t Multi \t Div \t Mod");
for (i = 0; i < Size; i++)
{
System.out.print(Addition[i] + " \t ");
System.out.print(Subtraction[i] + " \t ");
System.out.print(Multiplication[i] + " \t ");
System.out.print(Division[i] + " \t ");
System.out.print(Module[i]+ " \t ");
System.out.print("\n");
}
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac ArrayArithmeticOpert1.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ArrayArithmeticOpert1
Please Enter Number of elements in an array : 4
Please Enter 4 elements of an Array :
1
2
3
4
Please Enter 4 elements of an Array :
1
2
3
4

Add Sub Multi Div Mod


2 0 1 1 0.0
4 0 4 1 0.0
6 0 9 1 0.0
8 0 16 1 0.0

Object Oriented Programming Through Java Page 5


3.4 Assigning Array to Another Array
In Java, assigning one array to another doesn’t create a copy of the array but somewhat makes both variables
reference the same array.
If you modify the array through one reference, the change will be visible through the other reference as well.
Example:
public class ArrayAssignmentExample
{
public static void main(String[] args)
{
int[] originalArray = {1, 2, 3, 4, 5};
int[] anotherArray = originalArray; // Assignment, not a copy

// Modify the array through the anotherArray reference


anotherArray[0] = 10;

// Print both arrays


System.out.println("Original Array:");
for (int num : originalArray)
{
System.out.print(num + " ");
}

System.out.println("\nAnother Array:");
for (int num : anotherArray) {
System.out.print(num + " ");
}
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac ArrayAssignmentExample.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ArrayAssignmentExample.java
Original Array:
10 2 3 4 5
Another Array:
10 2 3 4 5

Object Oriented Programming Through Java Page 6


3.5 Dynamic Change of Array Size
 An array is a fixed size, homogeneous data structure.
 The limitation of arrays is that they're fixed in size. It means that we must specify the number of
elements while declaring the array.
 Here a question arises that what if we want to insert an element and there is no more space is left for the
new element? Here, the concept of dynamic array comes into existence. It expends the size of the array
dynamically.
 In the dynamic array, the elements are stored contiguously from the starting of the array and the
remaining space remains unused. We can add the elements until the reserved spaced is completely
consumed.
Example:
public class InitializeDynamicArray
{
public static void main(String[] args)
{

int array[] = new int[5];

System.out.print("Elements of Array are: ");

for(int i=0; i< array.length ; i++) //storing elements in array


{
array[i] = i+2;
}

System.out.println();
for(int i=0; i< array.length ; i++) //printing elements
{
System.out.print(array[i]+" ");
}

array = new int[10]; // changing size 5 to 10 create a new array with default values
System.out.println();
//printing elements
for(int i=0; i< array.length ; i++)
{
System.out.print(array[i]+" ");
}

}
}
Output:
Elements of Array are:
23456
0000000000

Object Oriented Programming Through Java Page 7


3.6 Sorting of Arrays, Search for Values in Arrays
a) Sorting of Arrays
 Sorting is a class of algorithms that are tasked with rearranging the positions of elements of an array
such that all of its elements are either in ascending or descending order.
Types of sorting techniques
 Bubble Sort
 Selection Sort
 Insertion Sort
 Merge Sort
Bubble Sort
 In bubble sort algorithm, array is traversed from first element to last element.
 Here, current element is compared with the next element. If current element is greater than the next
element, it is swapped
Process:
Step 1 − Check if the first element in the input array is greater than the next element in the array.
Step 2 − If it is greater, swap the two elements; otherwise move the pointer forward in the array.
Step 3 − Repeat Step 2 until we reach the end of the array.
Step 4 − Check if the elements are sorted; if not, repeat the same process (Step 1 to Step 3) from the last
element of the array to the first.
Step 5 − The final output achieved is the sorted array.
Program:
import java.util.Scanner;
public class BubbleSort
{
public static void bubbleSort(int[] arr)
{
int n = arr.length;
boolean swapped;

for (int i = 0; i < n - 1; i++)


{
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1]) // Swap arr[j] and arr[j + 1]
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
} // if close
} // inner for close

Object Oriented Programming Through Java Page 8


if (!swapped) // If no two elements were swapped in the inner loop, then break
{
break;
} //if close
} // outer for close
} // bubbleSort() close

public static void main(String[] args)


{
int size , i;
Scanner scan = new Scanner(System.in );

System.out.println("Enter size of an array");


size = scan.nextInt();

int[] arr = new int[size];

System.out.println("Enter array elements ");

for(i=0;i<size;i++)
{
arr[i] = scan.nextInt();
}

System.out.println("Array before sorting:");


printArray(arr);
bubbleSort(arr);
System.out.println("\nArray after sorting:");
printArray(arr);
} // main close
public static void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
}
} // class close
Output :
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac BubbleSort.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java BubbleSort
Enter size of an array
5
Enter array elements
15 64 91 46 76
Array before sorting:
15 64 91 46 76
Array after sorting:
15 46 64 76 91

Object Oriented Programming Through Java Page 9


Selection Sort
In selection sort algorithm, we search for the lowest element and arrange it to the proper location. We swap the
current element with the next lowest number.

Example:
import java.util.Scanner;
class SelectionSorting
{
public static void main(String ars[])
{
int arr[] = new int[100];
int n;
int i, j, min_idx;

Scanner scan = new Scanner(System.in);

System.out.println("Enter n value");
n = scan.nextInt();

System.out.println("Enter array elements");

for(i=0;i<=n-1;i++)
{
arr[i] = scan.nextInt();
}

Object Oriented Programming Through Java Page 10


// One by one move boundary of unsorted subarray

for (i = 0; i < n-1; i++)


{
// Find the minimum element in unsorted subarray
min_idx = i;

for (j = i+1; j < n; j++)


if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element

int temp = arr[min_idx];


arr[min_idx] = arr[i];
arr[i] = temp;
}

// Print the sorted array


System.out.println("Sorted array: \n");

for (i = 0; i < n; i++)


System.out.println(arr[i]);
System.out.println();

}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java SelectionSorting
Enter n value
5
Enter array elements
12
32
65
45
85
Sorted array:

12
32
45
65
85

Object Oriented Programming Through Java Page 11


InsertionSort:
We can create a java program to sort array elements using insertion sort.
Insertion is good for small elements only because it requires more time for sorting large number of elements.

Example:

import java.util.Scanner;
class InsertionSort
{
public static void main(String ar[])
{
int n, i, j, key;

Scanner scan = new Scanner(System.in);

System.out.println("Enter the number of elements: ");


n = scan.nextInt();

int arr[] = new int[n];

System.out.println("Enter the elements: ");

for (i = 0; i < n; i++)


{
arr[i] = scan.nextInt();
}

for (i = 1; i < n; i++)


{
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

Object Oriented Programming Through Java Page 12


System.out.println("Sorted array: ");
for (i = 0; i < n; i++)
{
System.out.print(" "+arr[i]);
}
}
}

Output:

Enter the number of elements:


6
Enter the elements:
22
66
13
54
98
48
Sorted array:
13 22 48 54 66 98

b) Searching techniques:
The linear search algorithm is defined as a sequential search algorithm that starts at one end and goes through
each element of a list until the desired element is found; otherwise, the search continues till the end of the
dataset
Program:
import java.util.Scanner;
class LinearSearch
{
public static void main(String ar[])
{
Int size , key, index = -1;
Scanner scan = new Scanner(System.in);

System.out.println("Enter the size of the array: ");


size = scan.nextInt();

int arr[] = new int[size];


System.out.println("Enter the elements");

for (int i = 0; i < size; i++)


{
arr[i] = scan.nextInt();
}

Object Oriented Programming Through Java Page 13


System.out.println("Enter the key to search for: ");
key = scan.nextInt();

for (int i = 0; i < size; i++)


{
if (arr[i] == key)
{
index = i;
break;
}
}

if (index != -1)
System.out.println("Key found at index "+index);
else
System.out.println("Key not found in the array");

}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java LinearSearch
Enter the size of the array:
6
Enter the elements
12
36
54
98
46
35
Enter the key to search for:
98
Key found at index 3

Object Oriented Programming Through Java Page 14


BinarySearch:
 Binary search is used to search a key element from multiple elements. Binary search is faster than linear
search.
 In case of binary search, array elements must be in ascending order. If you have unsorted array, you can
sort the array using Arrays.sort(arr) method
Procedure :
 The list must be sorted in ascending order.
 Binary search works on arrays or lists that allow random access (e.g., ArrayList in Java).
1. Initialize Pointers:
 Define two pointers, left and right, initially pointing to the start and end of the list respectively.

 left = 0 (index of the first element)

 right = array.length - 1 (index of the last element)

2. Search Loop:
 While left is less than or equal to right, continue searching.

 Calculate the middle index: mid = (left + right) / 2. This is the index where we will check for the

target element.
3. Comparison:
 Compare the target element with the element at the middle index array[mid].

 Three cases can occur:

 If array[mid] is equal to the target, then the element is found at index mid.
 If array[mid] is greater than the target, then the target (if it exists) must be in the left half
of the array. Adjust right = mid - 1 to search in the left sub-array.
 If array[mid] is less than the target, then the target (if it exists) must be in the right half of
the array. Adjust left = mid + 1 to search in the right sub-array.
4. Repeat:
 Repeat steps 2 and 3 until left is greater than right. This means the target element is not this
means the target element is not present in the array.
5. Result:
 If the target element is found during the search, return the index mid.
 If the target element is not found, return a specific value (e.g., -1) to indicate its absence.

Object Oriented Programming Through Java Page 15


Program:
import java.util.Scanner;
class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;

while( first <= last )


{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if ( arr[mid] == key)
{
System.out.println("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}

if ( first > last )


{
System.out.println("Element is not found!");
} // while close
} // binarySearch close

public static void main(String args[])


{
int arr[] = {10,20,30,40,50};

Scanner scan = new Scanner(System.in);

System.out.println(" Enter Element to search");


int key = scan.nextInt();

int last = arr.length-1;


binarySearch(arr,0,last,key);
}
} // class close
Output:
Enter Element to search
40
Element is found at index: 3

Object Oriented Programming Through Java Page 16


3.7 Class Arrays
The Arrays class in java.util package is a part of the Java Collection Framework.
This class provides static methods to dynamically create and access Java arrays.
It consists of only static methods and the methods of Object class. So,the methods of this class can be used by
the class name itself.
Some times when loops are used to do some tasks on an array like:
 Fill an array with a particular value.

 Sort an Arrays.

 Search in an Arrays.

 And many more.

Here Arrays class provides several static methods that can be used to perform these tasks directly without the
use of loops, hence forth making our code super short and optimized.

Syntax: Class declaration


public class Arrays extends Object
Syntax: In order to use Arrays
Arrays.<function name>;

Methods in Java Array Class


The Arrays class of the java.util package contains several static methods that can be used to fill, sort, search,
etc in arrays.

Methods Action Performed

sort() To sort the elements

Searches for the specified element in the array with the help of the Binary
binarySearch()
Search Algorithm

compare(array 1, array 2) Compares two arrays passed as parameters as er order.

Program (for Sort):


import java.util.Arrays;

class CodeForArraySorting
{
public static void main(String args[])
{
int[] arr = { 5, 2, 23, 7, 87, -42, 509 };

System.out.println("The original array is: ");

Object Oriented Programming Through Java Page 17


for (int num : arr)
{
System.out.print(num + " ");
}

Arrays.sort(arr);

System.out.println("\nThe sorted array is: ");


for (int num : arr)
{
System.out.print(num + " ");
}
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java CodeForArraySorting
The original array is:
5 2 23 7 87 -42 509
The sorted array is:
-42 2 5 7 23 87 509
Program (for binarySearch):
import java.util.Arrays;
public class CodeForArrayBinarySearch
{
public static void main(String[] args)
{
// Declaring and initializing byte arrays to search over them
byte byteArr[] = { 10, 20, 15, 22, 35 };
int intArr[] = { 10, 20, 15, 22, 35 };

// Using sort() method of Arrays class and passing arrays to be sorted as in arguments
Arrays.sort(byteArr);
Arrays.sort(intArr);
// Primitive datatypes to search
byte byteKey = 35;
int intKey = 22;

// Print commands where we are implementing


System.out.println(byteKey + " found at index = "+ Arrays.binarySearch(byteArr, byteKey));
System.out.println(intKey + " found at index = "+ Arrays.binarySearch(intArr, intKey));
}
}
Output:
35 found at index = 4
22 found at index = 3

Object Oriented Programming Through Java Page 18


3.8 Two-dimensional Arrays
 2D array can be defined as an array of arrays.
 The 2D array is organized as matrices which can be represented as the collection of rows and columns.
declare 2D Array:
int arr[max_rows][max_columns];
Memory Structure:

Code:
public class MatrixAdditionExample
{
public static void main(String args[])
{
//creating two matrices
int a[][] = {
{1,3,4},
{2,4,3},
{3,4,5} };
int b[][] = {
{1,3,4},
{2,4,3},
{1,2,4} };

int c[][] = new int[3][3]; //3 rows and 3 columns

for(int i=0;i<3;i++) //adding and printing addition of 2 matrices


{
for(int j=0;j<3;j++)
{
c[i][j] = a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println(); //new line
}
}
}
Output: D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java MatrixAdditionExample
268
486
469

Object Oriented Programming Through Java Page 19


3.9 Arrays of Varying Lengths
 when we created arrays of arrays (i.e. two-dimensional array), the arrays in the array were of same
length i.e. each row had the same number of elements.
 As each array in a multidimensional array is a separate array so it can have different number of
elements. Such arrays are known as non-rectangular arrays or ragged arrays.
 In order to create a two-dimensional ragged array, you have to first declare and instantiate the array by
specifying only the number of elements in the first dimension and leaving t he second dimension empty.
Example:
int [] [] table = new int [3] [];
 This statement declares an array object table of type int [] [] which references an array of 3 elements,
each of which holds a reference to a one-dimensional array.
 With the above statement, although three one-dimensional arrays have been declared but the number of
elements in each one dimensional array is still undefined. So you can

These statements define three possible one-dimensional arrays that can be referenced through the elements of
table array.
The first element (table [0]) now references an array of one element of type int.
The second element (table [1]) now references an array of two elements of type int.
The third element (table [2]) now references an array of three elements of type int.

Like you can initialize arrays of arrays, similarly, the ragged arrays can also be initialized.
Example :
int table [][] = {
{l},
{2,2},
{3,3,3}
};
creates an int-type two dimensional array table containing three array elements.
The first element is reference to a one-dimensional array of length one, the second element is reference to one-
dimensional array of length two and the third elements is a reference to one-dimensional array of length three.

Object Oriented Programming Through Java Page 20


You can access the elements of the ragged array just as before with the index pair but now the range of the
index for each subarray is different.
program that find maximum and minimum in ragged array
public class MaxMin
{
public static void main(String [] args)
{
int[][] table = {
{15,10} ,
{5,12,34},
{3,32,17,44}
};
int i, j,max,min;
max = min = table [0] [0];

for(i=0;i<table.length;i++)
{
for(j=0;j<table[i].length;j++)
{
if(table[i][j]>max);
max = table[i] [j];
if(table[i][j]<min)
min = table[i] [j];
}
}
System.out.println("Maximum Element is : "+max);
System.out.println("Minimum Element is : "+min);
}
}

Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java MaxMin
Maximum Element is : 44
Minimum Element is : 3

Object Oriented Programming Through Java Page 21


3.10 Three-dimensional Arrays
 An array with three indexes (subscripts) is called three dimensional array in Java.
Use of Three Dimensional Array:
 3-D array is useful when we want to handle a group of elements belonging to another group.
 Example: Suppose a college has three departments: Electronics, Computer Science, and Information
Technology.
 We can represent exam scores obtained by three students of each department in 3 different subjects like
this:
Electronics department:
student1 scores: 75, 87, 69
student2 scores: 90, 87, 85
student3 scores: 56, 67, 76
Computer Science department:
student1 scores: 78, 67, 75
student2 scores: 87, 98, 76
student3 scores: 67, 56, 65
Information Technology department:
student1 scores: 72, 63, 72
student2 scores: 82, 91, 71
student3 scores: 64, 56, 66
Syntax:
int[ ][ ][ ] scores = new int[3][3][3];
Program:
public class ThreeDArray
{
public static void main(String[] args)
{
String[ ] department = {"Electronics", "CS", "IT"};
int dept, st, sc, total = 0;
double perc = 0;

// Take the scores of students in a 3D array.


int[ ][ ][ ] scores = {
{ {75, 87, 69}, {90, 87, 85},{56, 67, 76} },
{ {78, 67, 75}, {87, 98, 76}, {67, 56, 66} },
{ {72, 63, 72}, {82, 91, 71}, {64, 56, 66} }
};

Object Oriented Programming Through Java Page 22


// Display the scores of students from 3D array.
for(dept = 0; dept < 3; dept++)
{
for(int i = 0; i < 3; i++)
{
System.out.println("Department " +department[i]+ ": ");
for(st = 0; st < 3; st++)
{
System.out.println("Student" +(st + 1)+ " scores: ");
for(sc = 0; sc < 3; sc++)
{
System.out.print(scores[dept][st][sc]+ " ");
total += scores[dept][st][sc];
perc = (double)total/3;
}
System.out.println("\nTotal scores: " +total);
System.out.println("Percentage: " +perc);
total = 0;
}
System.out.println();
}
break;
}
}
}

Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ThreeDArray
Department Electronics:
Student1 scores:
75 87 69
Total scores: 231
Percentage: 77.0
Student2 scores:
90 87 85
Total scores: 262
Percentage: 87.33333333333333
Student3 scores:
56 67 76
Total scores: 199
Percentage: 66.33333333333333

Object Oriented Programming Through Java Page 23


Department CS:
Student1 scores:
75 87 69
Total scores: 231
Percentage: 77.0
Student2 scores:
90 87 85
Total scores: 262
Percentage: 87.33333333333333
Student3 scores:
56 67 76
Total scores: 199
Percentage: 66.33333333333333

Department IT:
Student1 scores:
75 87 69
Total scores: 231
Percentage: 77.0
Student2 scores:
90 87 85
Total scores: 262
Percentage: 87.33333333333333
Student3 scores:
56 67 76
Total scores: 199
Percentage: 66.33333333333333

Object Oriented Programming Through Java Page 24


3.11 Arrays as Vectors
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of
elements in it as there is no size limit.
it is a part of Java Collection framework since Java 1.2. It is found in the java.util package
syntax:
Vector v = new Vector(); //without size
Vector v = new Vector(5,2); // its space will be increased by 2 when morethan 5 elements added
Java Vector Methods

S. Method Description
No

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the end of this Vector.

3) addElement() It is used to append the specified component to the end of this vector. It increases the vector size
by one.
4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

Code:
import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
Vector vec = new Vector<String>(); //Create a vector

//Adding elements using add() method of List


vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");

//Adding elements using addElement() method of Vector

vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}
Output: Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Object Oriented Programming Through Java Page 25


3.12 Introduction, Process of Inheritance
Definition:
 Getting properties from one class to another class is called inheritance
 When a Class extends another class it inherits all non-private members including fields and methods.
 extends (for classes) or implements (for interfaces) keywords are used to describe inheritance in Java.
 The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes.
 When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Purpose:

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Terms used in Inheritance:

 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
On above example
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.

Object Oriented Programming Through Java Page 26


3.13 Types of Inheritances

Types of inheritance in java (On the basis of class, there can be three types of inheritance in java)
1. single, 2. multilevel and 3. hierarchical.

SINGLE INHERITANCE
 When one class extends another class(Only one class) then we call it as Single inheritance.
 The below diagram represents single inheritance in java where Class B extends only one class Class A.
 Here Class B will be the Sub class and Class A will be one and only Super class.

Single Inheritance Example


class A
{
public void dispA()
{
System.out.println(" disp() method of Class A ");
}
}
public class B extends A
{
public void dispB()
{
System.out.println(" disp() method of Class B ");
}
public static void main(String args[])
{
B b = new B(); //Assigning ClassB object to ClassB reference
b.dispA(); //call dispA() method of ClassA
b.dispB(); //call dispB() method of ClassB
}
}
Output : disp() method of ClassA
disp() method of ClassB
Note: One and only one public class is allowed in one java file (Like 2 ,3 or 4 public classes not allowed)

Object Oriented Programming Through Java Page 27


MULTILEVEL INHERITANCE
 In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived
class act as the parent class to other class.
 In the below diagram, ClassB inherits the property of ClassA and ClassB act as a parent for ClassC.
 In Short ClassA parent for ClassB and ClassB parent for ClassC.

MultiLevel Inheritance Example

class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}

class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}
public class C extends B
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}

Object Oriented Programming Through Java Page 28


public static void main(String args[])
{
C c = new C(); //Assigning ClassC object to ClassC reference
c.dispA(); //call dispA() method of ClassA
c.dispB(); //call dispB() method of ClassB
c.dispC(); //call dispC() method of ClassC
}
}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC

HIERARCHICAL INHERITANCE
 In Hierarchical inheritance one parent class will be inherited by many sub classes.
 As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
 ClassA will be acting as a parent class for ClassB, ClassC and ClassD.

Hierarchical Inheritance Example


class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}
class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}

Object Oriented Programming Through Java Page 29


class C extends A
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}
}

class HierarchicalInheritanceTest
{
public static void main(String args[])
{
B b = new B();
b.dispB();
b.dispA();

C c = new C(); //Assigning ClassC object to ClassC reference


c.dispC(); //call dispC() method of ClassC
c.dispA(); //call dispA() method of ClassA
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA

Note:

Multiple inheritance is not supported in java through class but multiple and hybrid inheritance is supported
through interface only. When a class extends multiple classes i.e. known as multiple inheritance.

Object Oriented Programming Through Java Page 30


Why multiple inheritance is not supported in java?
To reduce the complexity and simplify of the language, multiple inheritance is not supported in java.
 Consider a scenario where A, B, and C are three classes.
 The C class inherits A and B classes.
 If A and B classes have the same method and you call it from child class object, there will be ambiguity
(doubt) to call the method of A or B class.
 Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.

Multiple inheritance is not supported through class in java, but it is possible by an interface, why?

 Multiple inheritance is not supported in the case of class because of ambiguity.


 However, it is supported in case of an interface because there is no ambiguity.
 It is because its implementation is provided by the implementation class.

MULTIPLE INHERITANCE

Multiple Inheritance is nothing but one class extending morethan one class.

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple
inheritance

Object Oriented Programming Through Java Page 31


Program:
interface Printable
{
public void print();
}
interface Showable
{
public void show();
}

class A7 implements Printable,Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
HYBRID INHERITANCE
 Hybrid Inheritance is the combination of both Single and Multiple Inheritance.
 Hybrid inheritance is also not directly supported in Java only through interface we can achieve this.
 As you can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting asParent for ClassD.

Object Oriented Programming Through Java Page 32


Example
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1 = new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
Output:
MethodA
MethodB
MethodC

Object Oriented Programming Through Java Page 33


3.14 Universal Super Class-Object Class
 Object class is present in java.lang package.
 If a Class does not extend any other class then it is direct child class of Object and if extends other
class then it is an indirectly derived.
 Therefore the Object class methods are available to all Java classes, So, Object class acts as a root
class inheritance hierarchy in any Java Program.
Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() Returns the class object of “this” object and used to get actual runtime class of
the object. It can also be used to get metadata of this class.

public int hashCode() Returns the hashcode number for this object. For every object, JVM generates a
unique number which is hashcode. It returns distinct integers for distinct objects.

public boolean equals(Object compares the given object to this object.


obj)
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds, until another
timeout)throws thread notifies (invokes notify() or notifyAll() method).
InterruptedException
public final void wait(long causes the current thread to wait for the specified milliseconds and nanoseconds,
timeout,int nanos)throws until another thread notifies (invokes notify() or notifyAll() method).
InterruptedException

public final void wait()throws causes the current thread to wait, until another thread notifies (invokes notify() or
InterruptedException notifyAll() method).

protected void finalize()throws is invoked by the garbage collector before object is being garbage collected.
Throwable

Object Oriented Programming Through Java Page 34


getClass() :
The java.lang.Object.getClass() method returns the runtime class of an object.
Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
Object obj1 = new String("Facebook");
ObjectgetClassExample obj2 = new ObjectgetClassExample();
System.out.println(" Class of Object obj1 is : " + obj1.getClass());
System.out.println(" Class of Object obj2 is : " + obj2.getClass());
}
}
Output
Class of Object obj1 is : class java.lang.String
Class of Object obj2 is : class ObjectgetClassExample
hashCode() Method
The hashCode() method returns the hash code for the Method class object.
Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
Object obj1 = new String("Facebook");
ObjectgetClassExample obj2 = new ObjectgetClassExample();
System.out.println("obj1 hashcode = " + obj1.hashCode());
System.out.println("obj2 hashcode = " + obj2.hashCode());
}
}
Output
obj1 hashcode = 561774310
obj2 hashcode = 1284693
Java equals()
 The java equals() is a method of lang.Object class, and it is used to compare two objects.
 To compare two objects that whether they are the same, it compares the values of both the objects
 By default, two objects will be the same only if stored in the same memory location.

Object Oriented Programming Through Java Page 35


Example:
public class ObjectgetClassExample
{
public static void main(String[] args)
{
String a = "Andhra";
String b = "Andhra";
String c="pradesh";

if(a.equals(b))
{
System.out.println(" a and b are equal " );
}
if(!a.equals(c))
{
System.out.println(" a and b are not equal " );
}
}
}
Output:
a and b are equal
a and b are not equal
toString() Method
 If you want to represent any object as a string, toString() method comes into existence.
 The toString() method returns the String representation of the object.
 If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output it can be the state of an object etc.
Advantage of Java toString() method
By overriding the toString() method ,we can return values of the object, so we don't need to write much code.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno = rollno;
this.name = name;
this.city = city;
}

Object Oriented Programming Through Java Page 36


public String toString() //overriding the toString() method
{
return rollno+" "+name+" "+city;
}

public static void main(String args[])


{
Student s1 = new Student(101,"Raj","mumbai");
Student s2 = new Student(102,"Vijay","chennai");
Student s3 = new Student(103,"Sai","Bangalore");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
System.out.println(s3); //compiler writes here s2.toString()
}
}
Output
101 Raj mumbai
102 Vijay chennai
103 Sai Bangalore

finalize() method
 This method is called just before an object is garbage collected.
 It is called the Garbage Collector on an object when the garbage collector determines that there are no
more references to the object.
 We should override finalize() method to set out of system resources, perform clean-up activities and
minimize memory leaks.
Note: The finalize method is called just once on an object even though that object is eligible for
garbage collection multiple times.
Example:
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());
t = null;
System.gc(); // calling garbage collector
System.out.println("end");
}

Object Oriented Programming Through Java Page 37


protected void finalize() // Overriding finalize()
{
System.out.println("finalize method called");
}
}

Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac Test.java
Test.java:16: warning: [removal] finalize() in Object has been deprecated and marked for removal
protected void finalize() // Overriding finalize()
^
1 warning
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java Test
523429237
end
finalize method called
Object Cloning in Java

 The object cloning is a way to create exact copy of an object.


 The clone() method of Object class is used to clone an object.
 The java.lang.Cloneable interface must be implemented by the class whose object clone we want to
create.
 If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
Syntax:
protected Object clone() throws CloneNotSupportedException
Use:
The clone() method saves the extra processing task for creating the exact copy of an object.
If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we
use object cloning.

Object Oriented Programming Through Java Page 38


Example:
class Student18 implements Cloneable
{
int rollno;
String name;

Student18(int rollno, String name)


{
this.rollno=rollno;
this.name=name;
}

public Object clone()throws CloneNotSupportedException


{
return super.clone();
}

public static void main(String args[])


{
try
{
Student18 s1 = new Student18(101,"amit");

Student18 s2 = (Student18)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}
catch(CloneNotSupportedException c)
{
}

}
}

Output:

101 amit
101 amit

Object Oriented Programming Through Java Page 39


3.15 Inhibiting Inheritance of Class Using Final
If you make any class as final, you cannot extend it.
Example:
final class Bike
{
}

class Honda1 extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda1();
honda.run();
}
}

Output:
Compile Time Error
3.16 Access Control and Inheritance
Refer page no: (unit-II pages 9-12 ) Topics 2.4 and 2.5
3.17 Multilevel Inheritance
Refer page Nos 28-29
3.18 Application of Keyword Super
 super keyword in java is a reference variable that is used to refer parent class object.
 super is an implicit keyword create by JVM and supply each and every java program
Uses of super at three levels
At variable level
At method level
At constructor level
Need of super keyword:
 Whenever the derived class is inherits the base class features, there is a possibility that base class
features are similar to derived class features and JVM will gets an ambiguity.
 In order to differentiate between base class features and derived class features must be preceded by
super keyword.
Syntax
super.baseclass feature

Object Oriented Programming Through Java Page 40


Super at variable level:
 In both base and derived class variables are same to differentiate those variables super keyword is used.
 If we are not writing super keyword before the base class data member name than it will be referred as
current class data member name and base class data member are hidden in the context of derived class.
Example
class Employee
{
float salary=10000;
}

class HR extends Employee


{
float salary=20000;
void display()
{
System.out.println(" Salary: "+salary); //print current class salary
System.out.println(" Salary: "+super.salary); //print base class salary
}
}

class Svariable
{
public static void main(String[] args)
{
HR obj = new HR();
obj.display();
}
}

Output
Salary: 20000.0
Salary: 10000.0

Object Oriented Programming Through Java Page 41


Super at method level
 The super keyword can also be used to invoke or call parent class method.
 In other word super keyword use when base class method name and derived class method name have
same name. (It should also be used in case of method overriding)
Example
class Student
{
void message()
{
System.out.println(" Good Morning Sir ");
}
}
class Faculty extends Student
{
void message()
{
System.out.println(" Good Morning Students ");
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}
public static void main(String args[])
{
Facultys = new Faculty();
s.display();
}
}

Output
Good Morning Students
Good Morning Sir

Object Oriented Programming Through Java Page 42


Super at constructor level
 The super keyword can also be used to invoke or call the parent class(base class) constructor.
 Super() It is used for calling super class default constructor from the context of derived class
constructors.
Example
class Employee
{
Employee()
{
System.out.println(" Employee class Constructor ");
}
}

class HR extends Employee


{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}

class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}

Output
Employee class Constructor
HR class Constructor

Object Oriented Programming Through Java Page 43


3.19 Constructor Method and Inheritance
 While implementing inheritance in a Java program, every class has its own constructor.
 Therefore the execution of the constructors starts after the object initialization. It follows a certain
sequence according to the class hierarchy.
 There can be different orders of execution depending on the type of inheritance.
Order of execution of constructor in Multilevel inheritance
In multilevel inheritance, all the upper class constructors are executed when an instance of bottom most child
class is created.
Program:
class College
{
College()
{
System.out.println("College constructor executed");
}
}

class Department extends College


{

Department()
{
System.out.println("Department constructor executed");
}
}

class Student extends Department


{

Student()
{
System.out.println("Student constructor executed");
}
}
public class OrderofExecution2
{
public static void main(String ar[]) /* Driver Code */
{

Student s = new Student();


}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java OrderofExecution2
College constructor executed
Department constructor executed
Student constructor executed

Object Oriented Programming Through Java Page 44


3.20 Method Overriding
Refer Unit-II 2.19 page Nos:36-37
3.21 Dynamic Method Dispatch (Runtime Polymorphism)
 Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
 In this process, an overridden method is called through the reference variable of a superclass.
 The determination of the method to be called is based on the object being referred to by the reference
variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

class A
{
}
class B extends A
{
}
A a=new B(); //upcasting
For upcasting, we can use the reference variable of class type or an interface type.
Example:
interface I
{
}
class A
{
}
class B extends A implements I
{
}
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.

Object Oriented Programming Through Java Page 45


Example of Java Runtime Polymorphism
class Bike
{
void run()
{
System.out.println(" running ");
}
}
class Splendor extends Bike
{
void run()
{
System.out.println(" running safely with 60km ");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
b.run();
}
}
Output:
running safely with 60km.
Explanation:
 In this example, we are creating two classes Bike and Splendor.
 Splendor class extends Bike class and overrides its run() method.
 We are calling the run method by the reference variable of Parent class.
 Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass
method is invoked at runtime.
 Since method call is determined by the JVM not compiler, it is known as runtime polymorphism.
Java Runtime Polymorphism Example: Shape
class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(" drawing rectangle... ");
}
}

Object Oriented Programming Through Java Page 46


class Circle extends Shape
{
void draw()
{
System.out.println(" drawing circle... ");
}
}

class Triangle extends Shape


{
void draw()
{
System.out.println(" drawing triangle... ");
}
}

class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;

s=new Rectangle();
s.draw();

s=new Circle();
s.draw();

s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members.

Object Oriented Programming Through Java Page 47


3.22 Abstract Classes
 Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Example: Sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)
Abstract class in Java
 A class which is declared as abstract using abstract keyword is known as an abstract class.
 It cannot be instantiated (object creation not allowed for abstract class directly).
 An abstract class can have a data member, abstract method, non-abstract method(method body), static
methods , final methods ,constructors, and even main() method.
 If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
 If there is an abstract method in a class, that class must be abstract.
 A method which is declared as abstract and does not have implementation called as abstract method.
Example: class A {
abstract void run();
}
Output: compile time error
abstract class A //abstract class
{
abstract void run(); //abstract method no method body and abstract
}
Example:
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely
Explanation: In the above example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.
Object Oriented Programming Through Java Page 48
Example 2:
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw() //In real scenario, implementation is provided by others i.e. unknown by end user
{
System.out.println(" drawing rectangle ");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println(" drawing circle ");
}
}

class TestAbstraction1
{
public static void main(String args[])
{
Shape s = new Circle1();
s.draw();
}
}
Output:
drawing circle

Object Oriented Programming Through Java Page 49


3.23 Interfaces and Inheritance
Refer page Nos 31-32
3.24 Introduction, Declaration of Interface
 In java, an interface is similar to a class, but it contains public abstract methods and public static final
variables only.
 We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.
Purpose:
The interface in java enables java to support multiple-inheritance.
The interface in Java is another mechanism to achieve abstraction (100% abstraction)
Points to Rember:
 The class that implements an interface must provide code for all the methods defined in the interface,
otherwise, it must be defined as an abstract class.
 The class uses a keyword implements to implement an interface.
 A class can implement any number of interfaces.
 We can not instantiate (object creation) an interface.
 All the members of an interface are public by default.
 An interface can extend multiple interfaces.
Understanding relationship between classes and interfaces
A class extends another class, an interface extends another interface but a class implements an interface.

Declaring Interfaces
Defining an interface is similar to that of a class. We use the keyword interface to define an interface.
Syntax
interface InterfaceName
{
members declaration;
}
Example
interface Emp
{
void learn(String str);
void work();
}

Object Oriented Programming Through Java Page 50


3.25 Implementation of Interface
Syntax

class className implements InterfaceName


{
...
body-of-the-class
}

Example

interface Emp
{
void learn(String str);
void work();
}

class Programmer implements Emp


{
public void learn(String str)
{
System.out.println(" Learn using " + str);
}

public void work()


{
System.out.println("Develop applications");
}
}

public class EmpTest


{
public static void main(String[] args)
{
Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}

Output
Learn using coding
Develop applications

Object Oriented Programming Through Java Page 51


3.26 Multiple Interfaces
 Multiple inheritances can be achieved through the use of interfaces.
 Interfaces are similar to classes in that they define a set of methods that can be implemented by classes

Step 1: Define the interfaces

interface Interface1
{
void method1();
}

interface Interface2
{

void method2();

Step 2: Implement the interfaces in the class


public class MyClass implements Interface1, Interface2
{
public void method1()
{
// implementation of method1
}
public void method2()
{
// implementation of method2
}

Step 3: Create an object of the class and call the interface methods
MyClass obj = new MyClass();

obj.method1();

obj.method2();

Object Oriented Programming Through Java Page 52


Program:

interface Printable
{
public void print();
}
interface Showable
{
public void show();
}

class A7 implements Printable,Showable


{
public void print()
{
System.out.println("Hello");
}

public void show()


{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

Object Oriented Programming Through Java Page 53


3.27 Nested Interfaces

 The interface that defined inside another interface is known as nested interface (inner interface).
 The nested interface declared within an interface is public by default.
 The nested interface declared within a class can be with any access modifier.
 Every nested interface is static by default.
Note:
 We can only access the nested interface by using outer interface or outer class name followed by
dot( . ), followed by the nested interface name.
Example
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface
{
public void outerMethod()
{
System.out.println("This is OuterInterface method");
}
}
class OnlyInner implements OuterInterface.InnerInterface
{
public void innerMethod()
{
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample
{
public static void main(String[] args)
{
OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

obj_1.outerMethod();
obj_2.innerMethod();
}
}
Output:
This is OuterInterface method
This is InnerInterface method

Object Oriented Programming Through Java Page 54


3.28 Inheritance of Interfaces

One interface can extends another interface like as shown below.


Syntax
interface InterfaceName1
{
members declaration;
}
interface InterfaceName2 extends InterfaceName1
{
members declaration;
}
Example:
interface Printable
{
void print();
}

interface Showable extends Printable


{
void show();
}

class A7 implements Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

Object Oriented Programming Through Java Page 55


3.29 Default Methods in Interfaces

 Java provides a facility to create default methods (from java 8 version) inside the interface.
 Methods which are defined inside the interface and tagged with default are known as default methods.
These methods are non-abstract methods.
Java Default Method Example:
 In the following example, Sayable is a functional interface that contains a default and an abstract
method.
 The concept of default method is used to define a method with default implementation.
 You can override default method also to provide more specific implementation for the method.
interface Sayable
{
default void say() // Default method
{
System.out.println("Hello, this is default method");
}
void sayMore(String msg); // Abstract method
}
public class DefaultMethods implements Sayable
{
public void sayMore(String msg) // implementing abstract method
{
System.out.println(msg);
}
public static void main(String[] args)
{
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Output:
Hello, this is default method
Work is worship

Object Oriented Programming Through Java Page 56


3.30 Static Methods in Interface
 Static Methods in Interface are those methods (from java 8 version) , which are defined in the
interface with static keyword
 Unlike other methods in Interface, these static methods contain the complete definition of the function
and since the definition is complete and the method is static, therefore these methods cannot be
overridden or changed in the implementation class.
 Similar to Default Method in Interface, the static method in an interface can be defined in the
interface, but cannot be overridden in Implementation Classes.
Program :
interface NewInterface
{
static void hello() // static method
{
System.out.println("Hello, New Static Method Here");
}
void overrideMethod(String str); // Public and abstract method of Interface
}
public class InterfaceDemo implements NewInterface // Implementation Class
{
public static void main(String[] args)
{
InterfaceDemo interfaceDemo = new InterfaceDemo();
NewInterface.hello(); // Calling the static method of interface
interfaceDemo.overrideMethod("Hello, Override Method here"); // Calling the abstract method
}
public void overrideMethod(String str) // Implementing interface method
{
System.out.println(str);
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java InterfaceDemo
Hello, New Static Method Here
Hello, Override Method here
Explonation:
 In this program, a simple static method is defined and declared in an interface which is being called in
the main() method of the Implementation Class InterfaceDemo.
 Unlike the default method, the static method defines in Interface hello(), cannot be overridden in
implementing the class.

Object Oriented Programming Through Java Page 57


3.31 Functional Interfaces
 An Interface that contains exactly one abstract method is known as functional interface (from java 8
version) .
 It can have any number of default, static methods but can contain only one abstract method. It can also
declare methods of object class.
 Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is a new
feature in Java, which helps to achieve functional programming approach.
Program:
interface sayable
{
void say(String msg);
}
public class FunctionalInterfaceExample implements sayable
{
public void say(String msg)
{
System.out.println(msg);
}
public static void main(String[] args)
{
FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
fie.say("Hello there");
}
}
Output:
Hello there
Java Predefined-Functional Interfaces
 Java provides predefined functional interfaces to deal with functional programming by using lambda and
method references.
 You can also define your own custom functional interface. Following is the list of functional interface
which are placed in java.util.function package.

Interface Description

BiConsumer<T,U> It represents an operation that accepts two input arguments and returns no result.

Consumer<T> It represents an operation that accepts a single argument and returns no result.

Function<T,R> It represents a function that accepts one argument and returns a result.

Predicate<T> It represents a predicate (boolean-valued function) of one argument.

Object Oriented Programming Through Java Page 58


3.32 Annotations
 Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or
fields to indicate some additional information which can be used by java compiler and JVM.
 Annotations in Java are used to provide additional information,
Built-In Java Annotations
There are several built-in annotations in Java. Some annotations are applied to Java code and some to other
annotations.
Built-In Java Annotations used in Java code
@Override
@SuppressWarnings
@Deprecated
Built-In Java Annotations used in other annotations
@Target
@Retention
@Inherited
@Documented
Understanding Built-In Annotations
@Override
@Override annotation assures that the subclass method is overriding the parent class method. If it is not so,
compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark @Override
annotation that provides assurity that method is overridden.
Program:
class Animal
{
void eatSomething()
{
System.out.println("eating something");
}
}

class Dog extends Animal


{

@Override
void eatsomething()
{
System.out.println("eating foods");
}
}

Object Oriented Programming Through Java Page 59


class TestAnnotation1
{
public static void main(String args[])
{
Animal a = new Dog();
a.eatSomething();
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac TestAnnotation1.java
TestAnnotation1.java:12: error: method does not override or implement a method from a supertype
@Override
^
1 error

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler .
import java.util.*;
class TestAnnotation2
{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}
}
Output:
Now no warning at compile time.
Note: If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time
because we are using non-generic collection

Object Oriented Programming Through Java Page 60

You might also like