0% found this document useful (0 votes)
20 views41 pages

Ooptj r23 Unit 3

Uploaded by

rahulswarna027
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)
20 views41 pages

Ooptj r23 Unit 3

Uploaded by

rahulswarna027
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/ 41

Object Oriented Through Java (23UCS12)

UNIT III

Arrays: Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer


Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to
Another Array, Dynamic Changeof Array Size, Sorting of Arrays, Search for Values in Arrays,
Class Arrays, Two-dimensional Arrays, Arrays of Varying Lengths, Three-dimensional Arrays,
Arrays as Vectors.
Inheritance: Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class-
Object Class, Inhibiting Inheritance of Class Using Final, Access Control and Inheritance,
Multilevel Inheritance, Application of Keyword Super, Constructor Method and Inheritance,
Method Overriding, Dynamic Method Dispatch, Abstract Classes, Interfaces and Inheritance.
Interfaces: Introduction, Declaration of Interface, Implementation of Interface, Multiple Interfaces,
Nested Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static Methods in
Interface, Functional Interfaces, Annotations.

1.Introduction to Arrays:
An Array is a collection of elements that share the same type and name. The elements from the
array can be accessed by the index.
An array is a structure consisting of a group of elements of the same type. When a large number
of data values of the same type are to be processed, it can be done efficiently by declaring an
array of the data type.

2. Declaration and Initialization of Arrays


The declaration of array starts with array type, followed by an identifier, and square brackets and
ends with semicolon as shown below:

Examples:
int numbers []; // an array of whole numbers
char name []; // A name is an array of characters
float priceList []; // An array of floating point numbers.
Initialization
With above declaration no memory is allocated. Memory is allocated when new operator is used
or when it is initialized with declaration as shown below.
int numbers []=new int[5]; //allocating memory with new
or int numbers[]={ 3,4,12,8}; //allocating with initialization
A two-dimensional array needs two square brackets one for rows and other for columns and may
be initialized as follow:
type identifier [][];// declaration of array of arrays
int total_sales[][]={{120,100,45},{30,45,60,},{80,90,70}}; //initialization

Alternative Array Declaration Syntax


In this declaration the type is followed by square brackets, and the name of the array follows the
square brackets.
type [] identifier; // declares one dimensional array
type [][] identifier; // declares two dimensional array
Example,
int [] numbers;
int [][] numbers, items, marks; // declares three arrays
This notation is useful when several arrays of same type are need to be declared.

3. Storage of Array in Computer Memory

SACET, CSE Department, II CSE I SEM ( R23) Page 1


The operator new, which is a keyword, allocates memory for storing the array elements.
For example, with the following declaration.
int[] numbers = new int[4];
Here, the compiler allocates 4 memory spaces, each equal to 4 bytes for storing the int type
values. When array is created as above the elements of the array are automatically initialized to
default values based on the type of array. Default values for int, float, char are 0,0.0, and space
respectively.

The declaration and initialization may as well be combined as:


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

A two-dimensional array may be declared and initialized as,


int [][] array2d = new int [][] {{1, 2, 3}, {4, 5, 6}}; or as
int [][] array2D = {{1, 2, 3}, {4, 5, 6}};

4. Accessing Elements of Arrays


The individual member of an array may be accessed by its index value. The index value
represents the place of element in the array. The first element space is represented by numbers
[0], and index value is 0. The memory space of the 2nd element is represented by number [1],
3rd element is number [2], and son on, and last element is number[n-1].
Note: the value of an array element is different from its index value.

5. Determination of Array Size:


The size of length of the array is determined by the following code:
int size=array_name.length;

Here, length is an attribute of array object


This size or length can be used in the for loop to access the elements as shown below:
for(int i=0;i<a.length;i++)
{
System.out.println(a[i] +”\n”);
}

Use of for–each Loop:


The for–each loop may be used to access each element of the one dimensional array.
for (int x: numbers)
{ System.out.println(x);
}

 For a two-dimensional array the nested for–each loops are used.


int TwoArray [][]= {{1,2,3},{4,5,7}};
for(int [] y : TwoArray)
{
for(int x : y)
System.out.print(x + “ ”);
System.out.println();
}

6. Array of Strings
 We can form array with elements as String as we have used primitive types.The String is
class in java standard library.
 Syntax: String s[]={“JAVA”, “FLAT”, “DBMS”};
Example,

SACET, CSE Department, II CSE I SEM ( R23) Page 2


class StrTest
{ public static void main(String arg[])
{ String str[]={"JAVA”, “FLAT”, “DBMS”};
for(String x:str)
{
System.out.println(x);
}
}
}

7. Operations on Array Elements


An array element is a variable of the type declared with array. All the operations that are
commonly performed on that type of a variable are also can be applied to an array element. The
operations such arithmetic addition, subtraction, multiplication, and division can be performed
on the elements of two arrays.
The new way of initializing the array is shown below.

Example program for Operations on Array Elements, ArrOperations.java


import java.util.*;
class ArrOperations
{
static void display(int a[])
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
public static void main(String arg[])
{ int [] arr1,arr2,arr3; // arrays declaration
int n,i;
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of the arrays:");
n=in.nextInt();
arr1=new int[n]; //memory allocation to array
arr2=new int[n];
arr3=new int[n];
//reading elements into array
System.out.println("Enter elements into arr1:");
for(i=0;i<n;i++)
{
arr1[i]=in.nextInt();
}
System.out.println("Enter elements into arr2:");
for(i=0;i<n;i++)
{
arr2[i]=in.nextInt();
}
System.out.println("Addition of two arrays is:");
for(i=0;i<n;i++)
{
arr3[i]=arr1[i]+arr2[i];
}
for(int i=0;i<arr3.length;i++)
{
System.out.print(arr3[i]+"\t");

SACET, CSE Department, II CSE I SEM ( R23) Page 3


}

}
}

Output:
D:/CSE>javac ArrOperations.java
D:/CSE>java ArrOperations
Enter the size of the arrays: 4
Enter elements into arr1:
2
4
6
8
Enter elements into arr2:
12
14
16
18
Addition of two arrays is:
14 18 22 26

8. Arrays as Parameters of Methods


We can pass Arrays as parameters similar to primitive data type and objects of class type.
Syntax:
display(arr1,arr2);
add(arr1,arr2);

These arguments in the method call are assigned to parameters in the method definition in the
order.
Example,
static void display(int a[])
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
static void add(int a[],int b[])
{
int c[]=new int[a.length];
System.out.println("Addition of two arrays is:");
for(int i=0;i<c.length;i++)
{
c[i]=a[i]+b[i];
}
display(c); //method call
}

9. Assigning Array to Another Array


Unlike in C and C++, in Java an array can be assigned to another array of same type. This
can be done as follows:
int arr1[]={2,4,6,8);
int arr2=arr1

In this process, the 2nd array (arr2) becomes a reference to the assigned array (arr1). The
second array is not a new array, instead a second reference is created. In this context both arr1
and arr2 are referring the same memory.
If a change is done on arr1, then it is reflected on arr2. Let us understand this with an example
program.

SACET, CSE Department, II CSE I SEM ( R23) Page 4


Example, Illustration of assigning of an array to another array
class AssignOneArraytoAnother
{
public static void main(String arg[])
{
int[] arr1,arr2; //declaration
arr1=new int[]{2,4,6,8}; //memory allocation and initialization to array
arr2=arr1; // assigning arr1 to arr2
System.out.println("Elements of arr2 are:"); //display arr2
for(int x:arr2)
System.out.print(x+"\t");
for(int i=0;i<arr1.length;i++)
arr1[i]=arr1[i]*5; //modifying the arr1 elements
System.out.println("\nElements of arr1 after modification are:"); //display arr1
for(int x:arr1)
System.out.print(x+"\t");
System.out.println("\nElements of arr2 after modification are:"); //display arr2
for(int x:arr2)
System.out.print(x+"\t");
}
} Output:

10. Dynamic Change of Array Size


 The number of elements (size) of the array may change during the execution of the
program.
 This feature is not present in C and C++.
 In Java, you may change the number of elements by dynamically retaining the array
name.
 In this process, the old array is destroyed along with the values of elements.
 Int arr1[]=new int[4];

Example Program on Dynamic Change of Array Size


class DynArrChange
{
public static void main(String arg[])
{
int[] arr1; //declaration
arr1=new int[]{2,4,6,8}; //memory allocation & initialization to array
System.out.println("Elements of arr1 are:");
for(int x:arr1)
System.out.print(x+"\t");
arr1=new int[6]; //dynamic change of array size
//display arr1
System.out.println("\nElements of arr1 after Size Change are:");
for(int x:arr1)
System.out.print(x+"\t");
}
}
Output:

SACET, CSE Department, II CSE I SEM ( R23) Page 5


11. Sorting of Arrays
Sorting means arranging the elements of an array so that they are placed in some relevant
order which may be either ascending or descending. Sorting refers to the operation of arranging
data in some given order, such as increasing or decreasing with numerical data or alphabetically
with character data.
Sorting of arrays is needed in many applications of arrays. Several methods are used for
sorting the arrays that include the following:
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort

1. Bubble Sort
 Bubble sort is a very simple method that sorts the array elements by repeatedly moving
the largest element to the highest index position of the array segment (in case of
arranging elements in ascending order).
 In bubble sorting, consecutive adjacent pairs of elements in the array are compared with
each other. If the element at the lower index is greater than the element at the higher
index, the two elements are interchanged. This process will continue till the list of
unsorted elements exhausts.
 This procedure of sorting is called bubble sorting because elements ‘bubble’ to the top of
the list. At the end of the first pass, the largest element in the list will be placed at its
proper position (i.e., at the end of the list).
 The basic methodology of the working of bubble sort is given as follows:
a) In Pass 1, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–2] is compared with A[N–1]. Pass 1
involves n–1 comparisons and places the biggest element at the highest index of the
array.
b) In Pass 2, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–3] is compared with A[N–2]. Pass 2
involves n–2 comparisons and places the second biggest element at the second highest
index of the array.
c) In Pass 3, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is
compared with A[3], and so on. Finally, A[N–4] is compared with A[N–3]. Pass 3
involves n–3 comparisons and places the third biggest element at the third highest index
of the array.
d) In Pass n–1, A[0] and A[1] are compared so that A[0]<A[1]. After this step, all the
elements of the array are arranged in ascending order.
Example : Let us consider an array A[] that has the following elements:
A[] = {30, 52, 29, 87, 63, 27, 19, 54}
Pass 1:
a) Compare 30 and 52. Since 30 < 52, no swapping is done.
b) Compare 52 and 29. Since 52 > 29, swapping is done. 30, 29, 52, 87, 63, 27, 19, 54
c) Compare 52 and 87. Since 52 < 87, no swapping is done.
d) Compare 87 and 63. Since 87 > 63, swapping is done. 30, 29, 52, 63, 87, 27, 19, 54
e) Compare 87 and 27. Since 87 > 27, swapping is done. 30, 29, 52, 63, 27, 87, 19, 54
f) Compare 87 and 19. Since 87 > 19, swapping is done. 30, 29, 52, 63, 27, 19, 87, 54
g) Compare 87 and 54. Since 87 > 54, swapping is done. 30, 29, 52, 63, 27, 19, 54, 87
 Observe that after the end of the first pass, the largest element is placed at the highest
index of the array. All the other elements are still unsorted.
Pass 2:
a) Compare 30 and 29. Since 30 > 29, swapping is done.

SACET, CSE Department, II CSE I SEM ( R23) Page 6


29, 30, 52, 63, 27, 19, 54, 87
b) Compare 30 and 52. Since 30 < 52, no swapping is done.
c) Compare 52 and 63. Since 52 < 63, no swapping is done.
d) Compare 63 and 27. Since 63 > 27, swapping is done. 29, 30, 52, 27, 63, 19, 54, 87
e) Compare 63 and 19. Since 63 > 19, swapping is done. 29, 30, 52, 27, 19, 63, 54, 87
f) Compare 63 and 54. Since 63 > 54, swapping is done.
29, 30, 52, 27, 19, 54, 63, 87
 Observe that after the end of the second pass, the second largest element is placed at the
second highest index of the array. All the other elements are still unsorted.
Pass 3:
a) Compare 29 and 30. Since 29 < 30, no swapping is done.
b) Compare 30 and 52. Since 30 < 52, no swapping is done.
c) Compare 52 and 27. Since 52 > 27, swapping is done. 29, 30, 27, 52, 19, 54, 63, 87
d) Compare 52 and 19. Since 52 > 19, swapping is done. 29, 30, 27, 19, 52, 54, 63, 87
e) Compare 52 and 54. Since 52 < 54, no swapping is done.
 Observe that after the end of the third pass, the third largest element is placed at the third
highest index of the array. All the other elements are still unsorted.
Pass 4:
a) Compare 29 and 30. Since 29 < 30, no swapping is done.
b) Compare 30 and 27. Since 30 > 27, swapping is done. 29, 27, 30, 19, 52, 54, 63, 87
c) Compare 30 and 19. Since 30 > 19, swapping is done. 29, 27, 19, 30, 52, 54, 63, 87
d) Compare 30 and 52. Since 30 < 52, no swapping is done.
 Observe that after the end of the fourth pass, the fourth largest element is placed at the
fourth highest index of the array. All the other elements are still unsorted.
Pass 5:
a) Compare 29 and 27. Since 29 > 27, swapping is done.
27, 29, 19, 30, 52, 54, 63, 87
b) Compare 29 and 19. Since 29 > 19, swapping is done. 27, 19, 29, 30, 52, 54, 63, 87
c) Compare 29 and 30. Since 29 < 30, no swapping is done.
 Observe that after the end of the fifth pass, the fifth largest element is placed at the fifth
highest index of the array. All the other elements are still unsorted.

Pass 6:
a) Compare 27 and 19. Since 27 > 19, swapping is done.
19, 27, 29, 30, 52, 54, 63, 87
b) Compare 27 and 29. Since 27 < 29, no swapping is done.
 Observe that after the end of the sixth pass, the sixth largest element is placed at the sixth
largest index of the array. All the other elements are still unsorted.
Pass 7:
a) Compare 19 and 27. Since 19 < 27, no swapping is done.

Example Program; BubbleSort.java


Class BubbleSort
{
static void display(int a[])
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
System.out.println();
}
static void bsort(int a[])
{ System.out.println("Sorted Elements are:");
//sorting procedure here
for(int i=0;i<a.length;i++)
{ //number of passes here
for(int j=0;j<(a.length-1);j++)
{
if(a[j]>a[j+1])
{
//swapping

SACET, CSE Department, II CSE I SEM ( R23) Page 7


int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
public static void main(String arg[])
{
int a[],i,j,n;
Scanner in=new Scanner(System.in);
System.out.println("Enter size of Array:");
n=in.nextInt();
a=new int[n];
//read element into array
System.out.println("Enter elements into array:");
for(i=0;i<n;i++)
{
System.out.printf("Enter %d Element",i);
a[i]=in.nextInt();
}
display(a);
bsort(a);
display(a);
}
}
Output:

12. Search for Values in Array


Searching refers to finding the position of a value in a collection of values. Searching
means to find whether a particular value is present in an array or not. If the value is present in the
array, then searching is said to be successful and the searching process gives the location of that
value in the array. If the value is not present in the array, the searching process displays an
appropriate message and in this case searching is said to be unsuccessful. Any searching
algorithm has two possible outcomes: either successful or unsuccessful.
Several searching algorithms are:
1. Linear search: It is used when data is in unordered fashion.
2. Binary search: It is used when data is in ordered fashion.
3. Fibonacci search: It is used when data is in ordered fashion.
4. Hashing: It is used when key is to be found in constant time.

1. Linear Search
Linear search, also called as sequential search, is a very simple method used for
searching an array for a particular value. It works by comparing the value to be searched with
every element of the array one by one in a sequence until a match is found. Linear search is
mostly used to search an unordered list of elements (array in which data elements are not sorted).
Example: Consider an unordered list L = { 10, 8, 2, 7, 3, 4, 9, 1, 6, 5 }
Working of Linear Search: Search element : 7

SACET, CSE Department, II CSE I SEM ( R23) Page 8


Example Program LinearSearch.java
import java.util.*;
class LinearSearch
{
public static void main(String arg[])
{
int a[],n,i,key,pos=0;
boolean b=false;
Scanner in=new Scanner(System.in);
System.out.println("Enter size of array:");
n=in.nextInt();
a=new int[n]; //creating array
//read elements into array
for(i=0;i<n;i++)
{
System.out.printf("Enter %d element:",i);
a[i]=in.nextInt();
}
System.out.println("Enter Key:");
key=in.nextInt();

//linear search starts


for(i=0;i<n;i++)
{
if(key==a[i])
{
b=true;
pos=i;
break;
}
}
if(b==true)
System.out.println(" The element found at :"+pos);
else
System.out.println(" The element not found");
}
}

2. Binary Search
 Binary search is a searching algorithm that works efficiently with a sorted list. Binary
search is a fast search algorithm with run-time complexity of Ο(log n).This search
algorithm works on the principle of divide and conquer.
 The middle element position is calculated by dividing the sum of lower bound and upper
bound by 2. i.e) if Low = first element position and High = last element position then
calculate the middle element position= (Low + High) /2 and compare searching element
with A[Mid ].
 The comparison of searching element with middle element yields the following cases:

SACET, CSE Department, II CSE I SEM ( R23) Page 9


a) If ( A[Mid] = = Search element) then search is successful.
b) If A[Mid] < Search element, then Search element will be present in the right
segment of the array. So, the value of Low will be changed as High = Mid Pos – 1
and again calculated the middle element position.
c) If A[Mid] > Search element, then Search element will be present in the left segment of
the array. So, the value of High will be changed as Low = Mid Pos + 1 and again
calculated the middle element position.
 Finally, if Search element is not present in the array, then eventually, High will be less
than Low. When this happens, the algorithm will terminate and the search will be
unsuccessful.
Working of Binary Search :
For a binary search to work, it is mandatory for the target array to be sorted.
For example, Consider an order list L = { 12, 21,34, 38, 45, 49, 67, 69, 78, 79, 82, 87, 93, 97,
99 }.
Let us search for the search element = 21 in the order list L. Initially, Low = 1, and High = 15
and calculate the middle element position.
Middle element position = ( Low + High ) / 2
= (1 + 15)/2 = 8

1. If (Search element = = A[Mid] )


21 = = 69 ( condition is false)
2. If (Search element < A[Mid] ) then High = Mid Pos - 1 and again calculate the Middle
element position.
21 < 69 then High = 8 – 1
=7
Mid Pos = ( Low + High ) / 2 = (1 + 7)/2
=4

1. If (Search element = = A[Mid] )


21 = = 38 ( condition is false)
2. If (Search element < A[Mid] ) then High = Mid Pos - 1 and again calculated the Middle
element position. 21 < 38 then High = 4 – 1
=3
Mid Pos = ( Low + High ) / 2 = (1 + 3)/2
=2

1. If (Search element = = A[Mid] )


21 = = 21 ( condition is true). Then search is successful

Example Program BinearySearch.java


import java.util.*;
class BinearySearch
{
public static void main(String args[])

SACET, CSE Department, II CSE I SEM ( R23) Page 10


{
int n,a[],item,first,last,middle;
//reading no.of elements
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements:");
n=in.nextInt();
a=new int[n];
//read elements into array
System.out.println("Enter elements into array:");
for(int i=0;i<n;i++)
a[i]=in.nextInt();
first=0;
last=n-1;
middle=(first+last)/2;
System.out.println("Enter element to search:");
item=in.nextInt();
//search process
while(first<=last)
{
if(a[middle]==item)
{
System.out.println("Item found at"+middle);
break;
}
else if(a[middle]<item)
{
first=middle+1;
}
else
{
last=middle-1;
}
middle=(first+last)/2;
}
if(first>last)
{
System.out.println("Item not found");
}
}
}

13. Class Arrays


 The package java.util defines the class Arrays with static methods.
 These methods can be applied on full array or part of the array.
Methods of Arrays class:
 Sorting – The class has defined several overloaded methods for sorting arrays of
different types.
 The sort() has the following overloaded methods.
i) public static void sort (int[] array)
ii) public static void sort(int[] array, int startIndex, endIndex) - This method sorts
the specified subset of the array of type int from startIndex to endIndex.
Searching(Binary search) –There are two versions of overloaded binary search methods that
are defined in the Array class.
1. public static int binarySearch(int [], int Key) –similar overloaded methods are
defined for other types such as byte, short, double etc; here the key is the value to
be searched, and it returns the position of the element where a match is found.
2. public static int binarySearch(double [], int startIndex, int endIndex, double Key)
– This will search key in between startIndex and endIndex.

Comparing – Here two arrays are compared. The outcome of the comparison will be a Boolean
value either true, or false.
 public static boolean equals (int[] a, int[] b)

SACET, CSE Department, II CSE I SEM ( R23) Page 11


Filling -This method is used to fill the entire array with the specified value as shown in the
following syntax.
 public static void fill(byte[], byte value) –fills entire array with value.
 public static void fill(byte[], int s_index, e_index, byte value) –fills the elements
from s_index to e_index, but e_index will not be included.
Copying –The following method copies the array into new array of specified length. If the
specified length is smaller than the original array length, then the remaining elements are cut-off.
 public static byte[] copyOf (byte[] original, int length)
 public static char[] copyOfRange(char[] original, int s_index,int e_index)
toString() method
 The method header is given as public static String toString (int [] array)
 The method returns a string representation of the array elements.
hashCode() method
 This method returns content-based hashCode of the array.
 public static int hashCode(float [] array) – it returns an integer corresponding the
array given as argument.
deepToString() method
 This method is used to convert the multidimensional array into string.
 public static String deepToString(object [] array)

Example Program for Arrays Class


import java.util.Arrays;
//sorting the elements
class ClassArrayFill
{
public static void main(String arg[])
{
int[] a={5,7,2,1,8,6,8,9};
int[] b={1,2,3};
float[] c={12.3f,4.5f,2.1f,6.54f,9.2f};
System.out.println("Arrays a and b are equal :"+Arrays.equals(a,b)); //equals test
Arrays.fill(c,1,3,25.3f); //filling the array
System.out.println("Contents of array C are:");
for(float x:c)
System.out.print(x+"\t");
System.out.println();

Arrays.sort(a); //Sorting the array

for(char x:a)
System.out.print(x+"\t");
System.out.println()

String s=Arrays.toString(a); //toString


System.out.println(s);

int arr2[]=Arrays.copyOf(b,b.length); //copying


System.out.println("Arr2 is :");

for(int x:arr2)
System.out.print(x+"\t");

System.out.println("The hashcode for array ‘a’ is:"+Arrays.hashCode(a)); //hash code


}
}

14. Two-Dimensional Arrays


An Array may hold arrays as its elements. If the elements of an array are one-dimensional
arrays, then it is called Two-dimensional array. In Java, 2-D array is treated as array of arrays.
Some of the examples for 2-D arrays are : Matrices, and Sales details in 4 quarters etc; A 2-D
array is created as follow:

SACET, CSE Department, II CSE I SEM ( R23) Page 12


int mat[][]=new int[3][5]; Here, mat is the name of the 2-D array, contains 3 arrays,
where each array contains 5 elements.
int [][] mat={{1,2,3,4,5},{4,5,6,7,8},{10,11,12,13,14,15}};

Example, Defining and Displaying 2-D Array - Operations on Arrays


import java.util.Arrays;
import java.util.*;
class MatTest
{
public static void main(String arg[])
{
int[][] A,B;
int r,c,i,j;
Scanner in=new Scanner(System.in);
System.out.println("Enter rows and columns:");
r=in.nextInt();
c=in.nextInt();

A=new int[r][c];
B=new int[r][c];
for(i=0;i<r;i++)//reading elements into matrix A
{
for(j=0;j<c;j++)
{
System.out.printf("Enter A[%d][%d] element:",i,j);
A[i][j]=in.nextInt();
}
}
for(i=0;i<r;i++) //reading elements into matrix B
{
for(j=0;j<c;j++)
{
System.out.printf("Enter B[%d][%d] element:",i,j);
B[i][j]=in.nextInt();
}
}
System.out.println("Matrix A is:"); //display arrays A and B
System.out.println(Arrays.deepToString(A));
System.out.println("Matrix B is:");
System.out.println(Arrays.deepToString(B));
C=new int[r][c];

//Matrix Addition
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("Matrix C is:");
System.out.println(Arrays.deepToString(C));
}
}

SACET, CSE Department, II CSE I SEM ( R23) Page 13


Code for Matrix Multiplication

Matrix Multiplication
// Check if multiplication is Possible
if (row2 != col1) {
System.out.println(
"\nMultiplication Not Possible");
}
else{
// Matrix to store the result. The product matrix will be of size row1 x col2
int C[][] = new int[row1][col2];
for (i = 0; i < row1; i++) { // Multiply the two matrices
for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}

15. Arrays of Varying Lengths


In Java, a two-dimensional array is treated as an array whose elements are one dimensional
arrays, which may have different sizes, that is, different number of elements. This is not possible
in C or C ++. A two-dimensional array may be declared asint a2D [][] = new int [3 ][];
The arrays may as well be declared as int array [][] = {{5, 7, 8 },{10, 11 }, {4, 3, 2, 7,5 }};

Example Program:

16. Three-Dimensional Arrays


Three–dimensional array is a complex form of a multidimensional array. A
multidimensional array is an array of arrays.
 A three dimensional can be defined as an array of two-dimensional arrays. When an array
holds two-dimensional arrays as its elements, the array is a three-dimensional array.
Each basic element of such an array needs three index values for its reference.
 The general definition of a Three-dimensional array is given below:
data_type [] [] [] array_name = new data_type [d1][d2][d3];
Where d1, d2, d3 = sizes of the dimensions
Syntax: Initialization of Three–dimensional array
• array_name[array_index][row_index][column_index] = value;

Example Program
class Three–dimensionalArrayEx
{
public static void main(String[] args)

SACET, CSE Department, II CSE I SEM ( R23) Page 14


{
int[ ][ ] [] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int z = 0; z < 2; z++)
System.out.println("arr[" + i + "][“+ j + "][“+ z + "] = “+arr[i][j][z]);
}
}
Output :
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

17. Arrays as Vectors


Vectors
 Similar to the arrays, vectors are another data structure.
 The Vectors can hold objects of any type( int, float)
 Using Vectors, we can implement Dynamic Arrays.
 The difference between Vectors and Arrays is, Vectors are dynamically allocated, where
Arrays are static.
 The Vector class is defined in java.util package.
 Vectors stores the pointers to the objects and not the objects themselves.
Vector Constructors
 The Vector class has the following constructors:
 Vector vec=new Vector() – Creates a default vector with initial size as 10
 Vector(int size) - Creates a Vector whose initial capacity is specified by size.
 Vector(int size, int incr) –Creates a Vector with initial capacity as size, and
increment of element is specified by incr. Here, the increment is the number of
elements added in each reallocation cycle.
Advantages
 Vectors are dynamically allocated
 Size of the vectors can be changed as and when required.
 They can store dynamic list of objects.
 The objects can be added or deleted from the vectors.
Important methods of Vector Class
 void add(int index, Object element) –Inserts the element at specified position.
 void addElement(Object element) –adds the element at the end of the vector, and
increases its size by one.
 void clear() –removes all the elements from the vector.
 int capacity() –returns the current capacity of the vector.
 int size() –returns the number of elements currently in the Vector.
 Object firstElement() -returns the first element from the vector
 Object lastElement() – returns the last element from the Vector
 Object get(int index) –returns the element at specified index.
 Object remove(int index) –removes the element at specified index.
Example Program VecTest.java
import java.util.*;
class VecTest
{
public static void main(String arg[])
{
Vector vec=new Vector(); //create vector
System.out.println("The capacity of Vector is:"+vec.capacity());
vec.addElement(40);
vec.addElement(50);
System.out.println("The current size of the vector is:"+vec.size());
Enumeration e=vec.elements();

SACET, CSE Department, II CSE I SEM ( R23) Page 15


while(e.hasMoreElements())
{
System.out.print(e.nextElement()+"\t");
}
System.out.println("Remove element at index1:"+vec.remove(1)); //deleting
element
e=vec.elements();
while(e.hasMoreElements())
{
System.out.print(e.nextElement()+"\t");
}
}
}

18. Introduction to Inheritance


Inheritance is the backbone of object-oriented programming (OOP). It is the mechanism by
which a class can acquire properties and methods of another class. Using inheritance, an already
tested and debugged class program can be reused for some other application. This class is often
termed as ‘base class’ or ‘Super class’. The other class that is created in this application will
inherit the fields and methods of the base class, and implements its own code. The following
terminology is used in this context.
 Super class This is the existing class from which another class, that is, the subclass is
generally derived. In Java, several derived classes can have the same super class.
 Subclass A class that is derived from another class is called subclass. In Java, a subclass
can have only one super class. This restriction is not present in C++, which supports
several base classes for the derived class.
Benefits of Inheritance
 It allows the reuse of already developed and debugged class program without any
modification.
 The super class is more general in its scope, where as the sub class is more specialized. It
allows a number of subclasses to fulfil the needs of several subgroups.
 A large program may be divided into suitable classes and subclasses that may be
developed by separate teams of programmers.
 The process of inheritance may or may not be stopped with one derived class. In fact,
another class, may be derived from the previously derived class. For example, class B is
derived from class A and class C is derived from class B.

19. Process of Inheritance


Inheritance means deriving some characteristics from something that is generic. In the
context of Java, it implies deriving a new class from an existing old class, that is, the super class.
A super class describes general characteristics of a class of objects. A subset of these objects
may have characteristics different from others. There are two ways of dealing with this problem.
First, make a separate class for the subset to include all the characteristics. Second, to have
another class that inherits the existing class, extend this class to include the special
characteristics. The keyword extends is used by the sub class to inherit the properties of super
class.
The syntax of the inheritance will be as follow:

Where B is derived class which is inheriting the properties, and class A is the super class from
which properties are acquired.

20. Types of Inheritance


The following types of inheritances are supported by Java.
i) Single Inheritance
ii) Multiple Inheritance using Interfaces
iii) Multilevel Inheritance
iv) Hierarchical Inheritance

SACET, CSE Department, II CSE I SEM ( R23) Page 16


v) Hybrid Inheritance

i) Single Inheritance
 In Single Inheritance one class extends another class (one class only). A subclass inherits
the properties of one super class.

Figure) Single Inheritance


 In above diagram, Class B inherits the properties of only Class A. Class A is a super class
and Class B is a Sub-class.
Example program for Single Inheritance:
class A
{
int i,j;
void setVal(int x,int y)
{
i=x;
j=y;
}
void add()
{
System.out.println("The sum is :"+(i+j));
}
}
class B extends A
{
void sub()
{
System.out.println("The subtraction is :"+(i-j));
}
}
class SingleInheritence
{
public static void main(String arg[])
{
B b=new B();
b.setVal(20,6);
b.add();
b.sub();
}
}

ii) Multiple Inheritance (Through Interfaces):


 Multiple Inheritance is one of the inheritance in Java types where one class extending
more than one class. Java does not support multiple inheritance. In java, we can achieve
multiple inheritances only through interfaces.

Figure) Multiple Inheritance


 In the above diagram, Class C extends Class A and Class B. A and B are the super classes
and C is a subclass.
iii). Multilevel Inheritance:
 In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.

SACET, CSE Department, II CSE I SEM ( R23) Page 17


 In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the
derived class also acts as the base class for other classes.

Figure: Multilevel Inheritance


 In the above diagram class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C. A is a super class, B is an intermediate class
and C is subclass. B inherits the properties of A and C inherits the properties of B and A .
Example program for Multilevel Inheritance:
class A
{
int i,j;
void setVal(int x,int y)
{
i=x;
j=y;
}
void add()
{
System.out.println("The sum is :"+(i+j));
}
}
class B extends A
{
void sub()
{
System.out.println("The subtraction is :"+(i-j));
}
}
class C extends B
{
void product()
{
System.out.println("The product is:"+(i*j));
}
}
class MultilevelInheritance
{
public static void main(String arg[])
{
C c=new C();
c.setVal(20,6);
c.add();
c.sub();
c.product();
}
}

iv). Hierarchical Inheritance:


 In Hierarchical Inheritance, one class serves as a superclass (base class)
for more than one subclass.

SACET, CSE Department, II CSE I SEM ( R23) Page 18


Figure: Hierarchical Inheritance
 In the above diagram, A is a super class. B, C and D are the sub classes. Class B, C, and
D inherit the properties of same class A. class A serves as a base class for the derived
classes B, C, and D.
Example Program for Hierarchical Inheritance:
class A {
void displayA()
{
System.out.println("***Super Class A***");
}
}
class B extends A {
void displayB()
{
System.out.println(".... Sub Class B");
}
}
class C extends A
{
void displayC()
{
System.out.println(".... Sub Class C");
}
}
class D extends A
{
void displayD()
{
System.out.println(".... Sub Class D");
}
}
public class HierarchicalInheritance
{ output:
public static void main(String[] args)
{
B b1 = new B();
b1.displayA();
b1.displayB();
C c1 = new C();
c1.displayA();
c1.displayC();
D d1 = new D();
d1.displayA();
d1.displayD();
} }

v) Hybrid Inheritance:
 Hybrid inheritance is one of the inheritance types in Java which is a combination of
Single and Multiple inheritance. When one or more types of inheritance are combined,
then it becomes a hybrid inheritance.
 Hence Java does not support hybrid inheritance as well with classes. But like
multiple inheritance, we can implement hybrid inheritance in Java using interfaces.

SACET, CSE Department, II CSE I SEM ( R23) Page 19


Figure) Hybrid Inheritance

 In the above diagram, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Disadvantages of Inheritance
 The tight coupling between super and subclasses increases and it becomes very difficult
to use them independently.
 Program processing time increases as it takes more time for the control to jump through
various levels of overloaded classes.
 When some new features are added to super and derived classes as a part of maintenance,
the changes affect both the classes.
 When some methods are deleted in super class that is inherited by a subclass, the methods
of subclass will no longer override the super class method.
The syntax of different types of inheritance:

21. Universal Super Class—Object Class


Object class is present in java.lang package. The Object class is the parent class of all
the classes in java by default.The object class is special class and it is at the top of the class
hierarchy. Hence, it is called Universal Super Class. Every class in Java is directly or indirectly
derived from the Object class. If a class does not extend any other class then it is a direct child
class of Object and if extends another class then it is indirectly derived. The declaration of the
object class will be as follow:
public class Object;

Methods of Object class:


The object class defines some common methods. These methods are as follow:
Method Description
public String toString() Returns the string representation of this object.
public int hashCode() Returns the hashcode number for the given object
public Boolean equals(Object obj) Compares the given object with this object. And returns

SACET, CSE Department, II CSE I SEM ( R23) Page 20


true if both are same, otherwise false.
public final class getClass() Returns the class object of this object to get metadata 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.
causes the current thread to wait for the specified
public final void wait() milliseconds and nanoseconds, until another thread
notifies

Example program for Object class:


class ObjectTest extends Object
{
void display()
{
System.out.println("Demo on Object class");
}
public static void main(String arg[])
{
ObjectTest t=new ObjectTest();
A a=new A();
A b=a;
String s=a.toString();
System.out.println(s);
System.out.println("HasCode is :"+a.hashCode());
System.out.println("Objects a and b are same:"+a.equals(b));
t.display();
}
}

22. Inhibiting (preventing) Inheritance of Class using Final


A class may be prevented from being inherited by other classes by declaring it using the
keyword ‘final’. When a class is declared with final keyword, it is called a final class. A final
class cannot be extended(inherited).The keyword is used in the following situations. If a class
definition is complete and if it is not required to be further sub-classed, it can be declared as
final. A class declared as final cannot be inherited further. Class variables or instance variables
are declared as final to make them as constants. When the keyword is used before the super class
method name, it prevents the method overriding.
//Example program to Illustrate the final class.
final class A
{
void dispA()
{
System.out.println("Method of class A");
}
}
class B extends A //here A cannot be inherited
{
void dispB()
{
System.out.println("Method of class B");
}
}
class FinalTest
{
public static void main(String arg[])
{
B b=new B();
b.dispA();
b.dispB();
}
}

SACET, CSE Department, II CSE I SEM ( R23) Page 21


23. Access Control and Inheritance
A derived class access to the members of a super class may be modified by access specifiers.
There are three access specifiers, that is, public, protected, and private. The syntax of specifying
access specifier is as follow:
Access-specifier type member_identifier;
Access Specifiers Access
No access specifier Access is permitted to any other class within the same package
public Access is permitted to any class in any package.
protected Access is permitted to any sub class in any package, also
within the same package.
private Access is permitted only to the members of the same class.
Examples:
private int i; // i is a private variable
public int j; // j is a public variable
protected int k; // k is a protected variable
int x; // x is a default access modifier variable
Java addresses five categories of visibility for class members:
Sl No Class member Private Default Protected Public
Member Member Member Member
1 Visible within same class YES YES YES YES
2 Visible within the same NO YES YES YES
package by subclasses
3 Visible within same NO YES YES YES
package by non-subclass
4 Visible within different NO NO YES YES
packages by subclasses
5 Visible within different NO NO NO YES
packages by Non-
subclasses

Example Program with default access specifier


package p1;
public class Protection
{
int n = 1; // n is a default access modifier variable
private int n_pri = 2; // n_pri is a private variable
protected int n_pro = 3; // n_pro is a protected variable
public int n_pub = 4; // n_pub is a public variable
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// System.out.println("n_pri = "+ n_pri); // class only
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
public class Demo {

SACET, CSE Department, II CSE I SEM ( R23) Page 22


public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
}
}

24. Applications of super keyword


The super keyword in java is a reference variable that is used to refer to super class objects.
 The keyword super can be used to access the super class instance variable.
Syntax: super.variablename;
 The keyword super can be used to access the super class method.
Syntax: super.methodname(parameter-list);
 Used in defining the sub class constructor. Super keyword can be used to calls the super
class constructor method from the sub class constructor.
Syntax: super(parameter-list);

// Example program for super keyword


class Person { // create a super class
int age; // instance variables
String name;
String empid;
int branchcode = 500;
void display()
{
System.out.println("WELCOME TO CSE DEPARTMENT");
}
Person(int age,String name,String empid) // Person is a super class constructor method;
{
this.age=age; //local variables are hiding instance variables So we have use this.
this.name=name;
this.empid=empid;
}
void displayPersonDetails()
{
System.out.println("*** EMPLOYEE DETAILS ***");
System.out.println(" *** Name: "+name);
System.out.println(" *** Age:"+age);
System.out.println(" *** Empid:"+empid);
}
}
class Employee extends Person {
// create a sub class
String job; // instance variables
float salary;
Employee(String eno,String n,int a, String job,float salary) // Employee is a sub class
constructor method;
{
super(a,n,eno); //calling the super class constructor method
super.display(); //calling the super class display() method

SACET, CSE Department, II CSE I SEM ( R23) Page 23


System.out.println("CSE BRANCH CODE: "+super.branchcode); //calling the super
classz variable
this.job=job; //local variables are hiding instance variables. So we have use this .
this.salary=salary;
}
void displayEmployeeDetails() {
displayPersonDetails(); // calling the super class method
System.out.println(" *** Job:"+job);
System.out.println(" *** Salary Rs:"+salary);
}
} //end of subclass
public class SuperExample {
public static void main(String args[]) {
Employee emp=new Employee("SACET180","Karth",25,"Software",90000);
emp.displayEmployeeDetails();
}
}
Output:

25. Constructor method and inheritance


A constructor is a block of code similar to the method. It is called when an instance of
the class is created. It is a special type of method which is used to initialize the object. Every
time an object is created using the new keyword, at least one constructor is called. A constructor
name must be the same as its class name and it should not return a value not even void.. A Java
constructor cannot be abstract, static, final, and synchronized. At the time of calling constructor,
memory for the object is allocated in the memory.
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. In multilevel inheritance, all the upper class constructors
are executed when an instance of bottom most child class is created.
Example , // Demonstrate on Constructor method and inheritance
class A
{
A()
{
System.out.println("Class A method");
}
}
class B extends A
{
B()
{
System.out.println("Class B method");
}
}
class C extends B
{
C()
{

SACET, CSE Department, II CSE I SEM ( R23) Page 24


System.out.println("Class C method");
} }
class ABC
{
public static void main(String args[])
{
System.out.println("Order of constructor execution in Multilevel Inheritance");
C c1=new C();
}
}

26. Method Overriding or Dynamic method dispatch or Runtime


polymorphism:
Method Overriding is one of the ways to implement Runtime Polymorphism.
Polymorphism is a concept in which method will take different forms in different environments.
Runtime polymorphism or Dynamic Method Dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time polymorphism.
Runtime Polymorphism in Java is achieved by Method overriding in which a sub class
overrides a method in its super class. An overridden method is essentially hidden in the super
class, and is not invoked unless the sub class uses the super keyword within the overriding
method.
Method overriding is an example of runtime polymorphism. When two methods with same name
and signature are defined in both super and sub class, the sub class definition will override the
definition of the super class when the method is called by the object of the sub class. This is
called ‘Method Overriding’.
Why Overridden Methods?
overridden methods allow Java to support run-time polymorphism. Overridden methods are
another way that Java implements the “one interface, multiple methods” aspect of
polymorphism. By combining inheritance with overridden methods, a superclass can define the
general form of the methods that will be used by all of its subclasses.
// A Java program to illustrate Method Overriding using hierarchical inheritance
class Shape {
void draw()
{
System.out.println("Drawing...");
}
}
class Rectangle extends Shape
{ Output:
void draw()
{
System.out.println("Drawing
Rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing
Circle...");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing Triangle...");
}
}
public class RuntimePolymorphism

SACET, CSE Department, II CSE I SEM ( R23) Page 25


{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
} }

27. Binding
There are two types of Bindings: static binding and dynamic binding
Static Binding: When binding is done at compile time by the compiler, it is known as Static
Binding, or Early Binding. Example, static, private, and final methods are bound at compile time.
Hence, these cannot be overridden.
Dynamic Binding: The Compiler not able to resolve the method call at compile time. This is
also called ‘Late Binding’. The method overriding is the best example for dynamic Binding.
The basic difference between static and dynamic binding is that static binding occurs at compile
time, whereas dynamic binding happens at run time.
Example Program for Static Binding StatBinding.java
class Vehicle {
final void display()
{
System.out.println("Vehicle Details");
}
}
class Car extends Vehicle{
void display()
{
System.out.println("Car Details");
}
}
class StatBinding {
public static void main(String arg[])
{
Car c=new Car();
c.display();
}
}
Output:
D:\CSE>javac StatBinding.java
StatBinding.java:10: error: display() in Car cannot override display() in Vehicle
void display()
^
overridden method is final
1 error
Example program for Dynamic Binding DynamicBinding.java
class Vehicle {
void display()
{
System.out.println("Vehicle Details");
}
}
class Car extends Vehicle {
void display()
{
System.out.println("Car Details");
}
}
class DynamicBinding {

SACET, CSE Department, II CSE I SEM ( R23) Page 26


public static void main(String arg[])
{
Vehicle c=new Car();
c.display();
}
}
28. Abstract Classes
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Any class that contains one or more abstract methods must also be
declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the
class keyword at the beginning of the class declaration. There can be no objects of an abstract
class. That is, an abstract class cannot be directly instantiated with the new operator. Such
objects would be useless, because an abstract class is not fully defined. You cannot declare
abstract constructors, or abstract static methods.
Abstract class can have abstract and non-abstract methods. Abstract class doesn’t
support multiple inheritance. Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.
 To declare an abstract class, use this general form:
abstract class Classname
{
Variables declaration;
Methods declaration;
}
To declare an abstract method, use this general form: abstract type name(parameter-list);
Example program for Abstract class:
import java.util.Scanner;
abstract class Shapes {
abstract void findTriangle(double b, double h);
abstract void findRectangle(double l, double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}
class FindArea extends Shapes {
void findTriangle(double b, double h)
{
double area = (b*h)/2;
System.out.println("Area of Triangle: "+area); Output:
}
void findRectangle(double l, double b)
{
double area = l*b;
System.out.println("Area of Rectangle: "+area);
}
void findSquare(double s)
{
double area = s*s;
System.out.println("Area of Square: "+area);
}
void findCircle(double r)
{
double PI =3.14;
double area = PI*r*r;
System.out.println("Area of Circle: "+area);
}
}
public class Areas {
public static void main(String args[])
{
double l, b, h, r, s;
FindArea area = new FindArea();
Scanner get = new Scanner(System.in);
System.out.print("\nEnter Base & Vertical Height of Triangle: ");

SACET, CSE Department, II CSE I SEM ( R23) Page 27


b = get.nextDouble();
h = get.nextDouble();
area.findTriangle(b, h);
System.out.print("\nEnter Length & Breadth of Rectangle: ");
l = get.nextDouble();
b = get.nextDouble();
area.findRectangle(l, b);
System.out.print("\nEnter Side of a Square: ");
s = get.nextDouble();
area.findSquare(s);
System.out.print("\nEnter Radius of Circle: ");
r = get.nextDouble();
area.findCircle(r);
}
}

29. Interfaces and Inheritance


Interface is an abstract way of defining the structure of a class. It is a collection of
abstract methods. An interface is declared by using the interface keyword. A class implements
an interface, thereby inheriting the abstract methods of the interface. A class uses
the implements keyword to implement an interface and it appears in the class declaration. An
interface is implicitly abstract. You do not need to use the abstract keyword while declaring an
interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Multiple Inheritance is one of the inheritance in Java types where one class extending more
than one class. Java does not support multiple inheritance. Multiple inheritance can be achieved
using the concept of interfaces in java.
Example Program for illustration of Multiple inheritance of interface:
interface One { double pi=3.14; } // interface defined
interface Two { double radius=10.0; }
interface Three { double area(); }
class Circle implements One, Two, Three // implements three interfaces
{
Public double area()
{
return pi*radius*radius;
}
}
class InterfaceDemo { // class with main method
public static void main(String args[])
{
Circle c=new Circle();
System.out.print(" Area of Circle = “+c.area());
}
}

30. Introduction Interfaces


Interface is an abstract way of defining the structure of a class. It is a collection of
abstract methods. An interface is declared by using the interface keyword. A class implements
an interface, thereby inheriting the abstract methods of the interface.
A class uses the implements keyword to implement an interface and it appears in the
class declaration. An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface. Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.

Similarities between Interface and Class


 Declaring an interface is similar to that of class; the keyword class is replaced by
keyword interface.
 Its accessibility can be controlled just like a class.
 An interface declared public is accessible to any class in any package, whereas the ones
without an access specifier is accessible to classes in the same package only.
 One can create variables as object references of interface that can use the interface.

SACET, CSE Department, II CSE I SEM ( R23) Page 28


 It can contain inner classes (nested classes) and inner interfaces.
 Since Java 8, an interface can have full definitions of methods with default or static
modifiers.

Dissimilarities between Class and Interface


 Interface cannot implement itself; it must be implemented by a class.
 An interface can contain only method headers followed by a semicolon.
 It cannot have the full definition of a method. The full definition is given in the class that
implements it.
 Java 8 modification allows the default and static method declarations in interfaces.
 The methods declared in the interface are implicitly public.
 An interface does not contain instance variables.
 The variables declared in an interface are implicitly public, static, and final.
 Interfaces cannot have a constructor like a class.
 An interface cannot extend a class nor can it have a subclass. It can only extend other
interfaces.
 A class can extend (inherit) only one class but an interface can extend any number of
interfaces (Multiple Inheritance).

31. Types of Interfaces


i) Top level interfaces
 It is an interface that is not nested in any class or interface.
 It comprises a collection of abstract methods.
 It can contain any number of methods that are needed to be defined in the class.
ii) Nested interface
 It is an interface that is defined in the body of a class or interface.
 In nested interfaces, one or more interfaces are grouped, so that it becomes easy to
maintain.
 It is referred to by the outer interface or class and cannot be accessed directly.
iii) Generic interface
 Like a class, an interface is generic if it declares one or more types of variables.
 It comprises methods that accept or return an object.
 Thus, we can pass any parameter to the method that is not of the primitive type.

32. Declaration of Interface


 Declaration of an interface starts with the access modifier followed by keyword interface.
 It is in turn followed by its name or identifier that is followed by a block of statements;
 These statements contain declarations of variables and abstract methods.
 The variables defined in interfaces are implicitly public, static, and final.
 They are initialized at the time of declaration.
 The methods declared in an interface are public, and abstract by default
Syntax for defining an Interface
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
... ……………………
return-type method-nameN(parameter-list);
type final-varnameN = value;
}.
Example
public interface Data
{
double PI=3.14; // final fields
void area(int r); //abstract methods
}
Members of Interface:
 The members are declared in the body of the interface.
 The members inherited from any super interface that it extends.
 The methods declared in the interface are implicitly public abstract member methods.
 The field variables defined in interfaces are implicitly public, static, and final.

SACET, CSE Department, II CSE I SEM ( R23) Page 29


 The field variables declared in an interface must be initialized; otherwise, compile-type
error occurs.
 Since Java SE8, static and default methods with full definition can also be members of
interface.
33. Implementation of Interface
 Once an interface has been defined, one or more classes can implement that interface.
Declaration of class that implements an interface
Syntax for implementing Interfaces:
class classname implements interfacename
{
// class-body
}

 If a class extends another class as well as implements interfaces, it is declared as

For example, implements Multiple Inheritance using Interfaces:


 Multiple Inheritance is one of the inheritance type in Java where one class extending
more than one class. Java does not support multiple inheritance. Multiple inheritance can
be achieved using the concept of interfaces in java.
Syntax:
interface Interface1 {
//Interface1 body
}
interface Interface2 {
//Interface2 body
}
class subclassname implements Interface1, Interface2
{
// class-body
}
Example Program for Multiple Inheritance using Interfaces
import java.util.Scanner;
interface Interface1
{
void add(int x ,int y);
void average(double x, double y , double z );
}
interface Interface2
{
void mul(double p , double q);
}
class Test implements Interface1, Interface2
{
public void add(int x, int y)
{
int sum=x+y;
System.out.println("SUM :"+sum);
}
public void average(double a, double b, double c)
{
double avg=(a+b+c)/3;
System.out.println("AVERAGE:"+avg);
}
public void mul(double p, double q)
{
double m=p*q;
System.out.println("MULTIPLICATION:"+m);

SACET, CSE Department, II CSE I SEM ( R23) Page 30


}
}
public class MultipleInheritanceDemo
{
public static void main(String args[])
{
Test obj = new Test();
Scanner in = new Scanner(System.in);
System.out.println("***INTERFACE1 DATA***"); Output:
System.out.print("Enter x value: ");
int x = in.nextInt();
System.out.print("Enter y value: ");
int y= in.nextInt();
obj.add(x,y);
System.out.print("Enter a value: ");
double a = in.nextDouble();
System.out.print("Enter b value: ");
double b = in.nextDouble();
System.out.print("Enter c value: ");
double c = in.nextDouble();
obj.average(a,b,c);
System.out.println("***INTERFACE2
DATA***");
System.out.print("Enter p value: ");
double p = in.nextDouble();
System.out.print("Enter q value: ");
double q = in.nextDouble();
obj.mul(p,q);
}
}

34. Multiple Interfaces


Like Single interface, Multiple interfaces can also be implemented in Java. For this, the class
implements all the methods declared in all the interfaces. When the class is declared, names of
all interfaces are listed after the keyword implements and separated by comma. As for example,
if class A implements interfaces C and D, it is defined as

Interface References:
An interface reference can only access the methods declared in that interface. It cannot access
other methods of the class implementing that interface. For interface references, variables can be
declared as object references. In this case, the object reference would use interface as the type
instead of class. The appropriate method is called on the basis of actual instance of the interface
that is being referred to. If the implementing class has methods other than definitions of abstract
methods, these methods cannot be called with interface reference object. Such methods have to
be called with object of implementing class.
// Illustration of implementing multiple interfaces with Interface References
interface InterfaceA
{
void show();
}
interface InterfaceB
{
void add(int a,int b);
}
class MultiInterface implements InterfaceA, InterfaceB
{

SACET, CSE Department, II CSE I SEM ( R23) Page 31


public void show() // InterfaceA method
{
System.out.println(“Hello! this is InterfaseA method");
}
public void add(int x,int y) // InterfaceB method
{
System.out.println("Sum is :"+(x+y));
}
void sub(int x,int y) // class method
{
System.out.println("subtraction is:"+(x-y));
}
}
class MultiInterfaceTest
{
public static void main(String arg[])
{
// creating interface references and assigning class object
InterfaceA i1=new MultiInterfaceImpliment ();
i1.show(); // invoking the InterfaceA method
InterfaceB i2=new MultiInterfaceImpliment (); //here i2 is interface reference
object
i2.add(9,3); // invoking the InterfaceB method
MultiInterface m1=new MultiInterface();
m1.sub(9,3); //sub() is the method of implementing class
}
}
Stub Methods :
If a class implements an interface, it has to define all its abstract methods; if we fail to do
so, then it will make the implementing class an abstract class. In several cases, we do not need to
define all the methods because we need only a few of these. In order to meet the requirement, we
define stub methods for the methods we do not need. A stub method does not do anything;
however, it fulfils the requirement.
// Illustration of definitions of stub methods
interface AreaVolume {
double surfaceAreaSphere (double radius);
double volumeShpere (double radius);
void setValue (double side);
} // end of interface
public class StubMethod {
double surfaceAreaSphere (double radius) //Definition of stub method for
surfaceAreaSphere
{
return 0;
}
void setvalue (double side) {}//Definition of stub method for setValue
double volumeSphere (double radius) // definition of method that is implemented
{
return 4.0*Math.PI* Math.pow(radius, 3)/3 ;
}
public static void main(String[] args) { // main method
StubMethod stm = new StubMethod();
System.out.printf(“Volume of sphere of radius 10 = %.2f \n”,
stm.volumeSphere(10.0));
}
}
Output:Volume of sphere of radius 10 = 4188.79

35. Nested Interfaces


An interface may be declared as a member of a class or in another interface. In the
capacity of a class member, it can have the attributes that are applicable to other class members.

SACET, CSE Department, II CSE I SEM ( R23) Page 32


In other cases, an interface can only be declared as public or with default (no-access modifier)
access.
Syntax of nested interface in another interface is given as
interface Interface_identifier // outer interface
{
………………
interface Nested_Interface_identifier // inner interface
{
……………..
}
}
Example, Illustration of nested interface in a class
class A
{
interface Nested
{
int max(int x, int y); Output:
}
}
class B implements A.Nested
{
public int max(int x,int y)
{
return x>y?x:y;
}
}
class NestedTest {
public static void main(String arg[]) {
B b1=new B();
System.out.println("The max of two numbers:"+b1.max(9,6));
}
}
// Illustration of nested interface in an interface
interface Shape // outer interface
{
double getArea(double x);
interface Display // inner interface
{
void show();
}
}
class A implements Shape, Shape.Display {
public double getArea(double r)
{
double PI=3.14; Output:
return PI*r*r;
}
public void show()
{
System.out.println("Nested interfaces
Demo");
}
}
class NestedTest {
public static void main(String arg[])
{
A a=new A();
System.out.println("Area of Circle:"+a.getArea(2));
a.show();
}
}

SACET, CSE Department, II CSE I SEM ( R23) Page 33


36. Inheritance of Interfaces
An interface also can extend another interface using the keyword ‘extends’. The code is
similar to extending the properties from the ‘class’.
Syntax:
interface Interface1
{
//body of Interface1
}
interface Interface2
{
//body of Interface2
}
interface Interface3 extends Interface1, Interface2
{
//body of Interface3 // Here, interface3 extends the properties from interface2 and
Interface3
}
// Illustrates the inheritance of interfaces and implementation by class
interface One
{
double PI=3.14;
}
interface Two
{
double r=2.0;
}
interface Three extends One,Two // // extending interface
{
void area();
}
class Circle implements Three { // implementing interface
public void area() {
double a=PI*r*r;
System.out.println("Area is:"+a);
}
}
class InheritanceOfInterface output:
{
public static void main(String arg[])
{
Circle c1=new Circle();
c1.area();
}
}

37. Default Methods in Interfaces


The Java SE8 enhancement of interfaces allows the interfaces to have full definitions of
default and static methods. A class that implements an interface must define all the abstract
methods of the interface. Now, if at a later stage, it is required to introduce another abstract
method to the interface, then all the classes implementing the interface must be modified. To
overcome this problem, the following two options are available in the existing (before Java SE8)
arrangement.
A default method is declared with keyword default as

Restrictions to default methods


 If a class implements two or more interfaces, the interfaces cannot have default methods
with the same signature because this would cause ambiguity as to which one to execute.

SACET, CSE Department, II CSE I SEM ( R23) Page 34


 In the case of methods with the same name, the compiler would choose by matching
parameters.
 If the class that is implementing the interfaces also defines the method with the same
name, then class definition has priority over other definitions.
 A default method cannot be declared final.
Example 1, // Illustration of default method in interface
interface J8Inface
{
int num=9;
default void display()
{
System.out.println("2 to the power 2 is :"+Math.pow(2,2));
}
} Output:
class DefaultMethodTest implements J8Inface{ area = 81
public static void main(String arg[]) 2 to the power 2 is : 4.0
{
DefaultMethodTest dm=new DefaultMethodTest ();
int area = number* number;
System.out.println(“area =” +area );
dm.display();
}
}
Example 2 , // Illustration of inheritance of interfaces by using default method
interface InfaceA {
public void showA();
default public void display()
{
System.out.println(“Good morning to everyone”);
}
}
interface InfaceB extends InfaceA {
public void showB();
default public void display()
{
System.out.println(“Good bye to everyone”);
}
}
class DefaultMethodB implements InfaceB {
public static void main(String args[])
{
public void showA()
{
System.out.println(“It is Interface A”);
}
public void showB()
{
System.out.println(“It is Interface B”);
}
DefaultMethodB d = new DefaultMethodB();
d.showA();
d.display(); //display() method is accessed for the interface InfaceA.
d.showB();
}
}

Example 3 , // Default method declared as final


interface A{
public void show();
final default public void display() // error due to final
{
System.out.println(“Good morning to everyone”);

SACET, CSE Department, II CSE I SEM ( R23) Page 35


}
}
class DemoC implements A
{
public void show()
{
System.out.println(“It is Interface”);
}
public static void main(String args[])
{
DemoC d = new DemoC();
d.show();
d.display();
}
}
Output: compilation error

38. Static Methods in Interface


The Java version 8 allows full definition of static methods in interfaces. A static method is a
class method. For calling a static method, one does not need an object of class. It can simply be
called with class name as class_name.method_name(); Static methods are called with
Interface name as interfacename.method(). A class that implements an interface also inherits
all its static methods. The inherited method is also a class method, and therefore, the method can
simply be called by using class name as illustrated.
Example, // Illustration of static method in interface
interface InFace1 // defining an interface
{
int number =1000;
static void compute (int num) // static method defined
{
Output
int cube = num * num * num ;
Cube root of 1000 = 10.0
System.out.println( “Cube of” + num +
Cube of 10 = 1000
“ = ” + cube );
}
}
public class StaticMethod implements InFace1 // implementing an interface
{
public static void main(String[] args) {
StaticMethod sm = new StaticMethod(); // creating object
//The Java Math.cbrt() method returns the cube root of the specified number.
//Here, cbrt() is a static method. Using number defined in interface
System.out.println(“Cube root of 1000 = ” + Math.cbrt(number));
InFace1.compute(10); //static method is called with interface name
}
}

39. Functional Interfaces


In Java SE8, a new package java.util.function on functional interfaces has been
introduced for writing Lambda functions. There are some predefined functional interfaces in
Java like Function, BinaryOperator, Predicate, Consumer, Supplier etc. Functional interfaces are
interfaces with one abstract method. They are also called SAM or single abstract method type.
However, a functional interface can have more than one static and default methods. If the
functional interface contains more than one abstract method, the compiler will throw an error.
There are several situations where we need to pass the methods as arguments to other methods,
this is possible through functional interface.
Predicate: The Predicate interface has an abstract method test which gives a Boolean value as a
result for the specified argument. Its prototype is
public interface Predicate
{
public boolean test(T t);
}

SACET, CSE Department, II CSE I SEM ( R23) Page 36


BinaryOperator: The BinaryOperator interface has an abstract method apply which takes two
arguments and returns a result of same type. Its prototype is:
public interface BinaryOperator
{
public T apply(T x, T y);
}
Function: The Function interface has an abstract method apply which takes argument of type T
and returns a result of type R. Its prototype is
public interface Function
{
public R apply(T t);
}
Example1, //Illustration of uses of functional interfaces Function and BinaryOperator
import java.util.function.Function;
import java.util.function.BinaryOperator;
public class BiOperator
{
public static void main(String args[])
{
Function <Double, Double>logrithm = Math::log;
// method reference assigned to Function
System.out.println( “log of 10 to the base e = ” + logrithm.apply(10.0));
// apply() method performs the operation on the given arguments and returns the
function result.// method reference assigned to BinaryOperator
BinaryOperator<Integer> minimum = Math::min;
System.out.println (“Minimum of 20 and 46 is ” + minimum.apply(20, 46));
}
}

Output: log of 10 to the base e = 2.302585092994046


Minimum of 20 and 46 is 20

Table: Some standard functional interfaces of package java.util.function

SACET, CSE Department, II CSE I SEM ( R23) Page 37


Example2, //Illustration of application of predicates in filtering arrays
import java.util.function.Predicate;
public class PredicateEx {
public static void main(String[] args) { // main class
//isEqual() is used to compare strings with string “Chirala” to test if they are equal.
Predicate<String>str = Predicate.isEqual("Chirala"); output:
// using Predicate to test for "Chirala"
System.out.println(str.test("Chirala"));
String [] names={"Bapatla", "Ongole" ,
"Chirala"};
for(int i =0; i<names.length; i++)// for loop
if (str.test (names[i]))
System.out.println(names[i]);
for(String s: names) // filtering the array
if (!str.test(s))
System.out.print(s +" ");
}
}

Functional Consumer<T>
It declares one abstract method void accept(T t). The method only consumes its
argument. It does not give any return value. This is mainly used to display or to set the values.
The interface declaration is @FunctionalInterface
public interface Consumer
{
void accept(T t);
}
Example Program,
import java.util.function.Consumer;
class FunTest{
static void disp(double t)
{
System.out.println(t+"\t");
}
public static void main(String arg[]) {
Consumer<Double>consumer=(Double d)->{disp(d);};
consumer.accept(3.14);
}
}
Functional Supplier
The functional Supplier is opposite to the Consumer. It simply supplies an object through its
method get(), which does not take any argument.This method can be used in a situation where
there is no input, but there is output. The declaration of the function is as follow:
@FunctionInterface
public interface Supplier
{
T get();
}
Example Program,
import java.util.function.Supplier;
class MyNumber
{ int getNumber()
{
return (int) (Math.random()*100);
Output:
}
D:\CSE>java SupplierTest
}
The new number is:42
class SupplierTest
{
public static void main(String arg[])
{
Supplier<MyNumber> supplier=MyNumber::new;
MyNumber number=supplier.get();//supplies an object as argument

SACET, CSE Department, II CSE I SEM ( R23) Page 38


System.out.println("The new number is:"+number.getNumber());
}
}

40. Annotations
Annotation framework in Java language was first introduced in Java 5 through a
provisional interface. It is a type of metadata that can be integrated with the source code without
affecting the running of the program. Annotations may be retained(continued) up to runtime and
may be used to instruct the compiler and runtime system to do or not to do certain things. Since
Java SE 8, the annotations may be applied to classes, fields, interfaces, methods, and type
declarations like throw clauses. The annotations are no longer simply for metadata inclusion in
the program but have become a method for user’s communication with compiler or runtime
system.
For example, consider a super class method that is overridden in the sub class. In this
context both methods signatures must be same (Example; method name, list of arguments and
their types) If, by mistake, a type or parameter in the sub class definition is changed, then method
overriding will no longer work, instead it becomes method overloading. In this situation the
program will still compile without any error, but the result will not be as expected. It is difficult
to catch such error. The solution to it is to add annotation before the sub class method name as
follow: @Override. This will cause the compiler to check and report whether this is a overridden
method or not. In this way it helps program to catch error.

Example Program,
class X
{
void add(int x, double y) //int and float as parameters
{
System.out.println("Floating point Sum is :"+(x+y));
}
}
class Y extends X
{
@Override
void add(int x, int y) // integers as paramters
{
System.out.println("Integer Sum is :"+(x+y));
}
}
class AnnoTest
{
public static void main(String arg[])
{
Y y=new Y();
y.add(2,3.4);
}
}

Benefits of using Annotations


 It provides useful information to the compiler for detecting errors.
 The information may also be used for suppressing warnings.
 Annotations may be used for generating code in xml (Xtensible Markup Language).
 Annotation may be retained (Continued) up to runtime.
 It can carry metadata up to runtime and the information may be obtained at runtime.
Retention Policy
 This specifies how long the annotation retained in the program.
 This is directed by another annotation called @Rentention.
 This has three options as follow:
• @Retention(RetentionPolicy.SOURCE ) - Retained in the source file and
discarded at compile time.
• @Retention(RetentionPolicy.CLASS) – The annotation goes up to the .class file.
It is part of compiled program, but cannot go further.
• @Retention(RetentionPolicy.RUNTIME) – This is accessible up to runtime.

SACET, CSE Department, II CSE I SEM ( R23) Page 39


Predefined 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 –sub class overrides super class method
• @SuppressWarnings – it is used to suppress the warnings issued by compiler.
• @Deprecated –It informs the user that this method will be removed in the future.
 Built-In Java Annotations used in other annotations
• @Target -is used to specify at which type, the annotation is used.
• @Retention- is used to specify to what level annotation will be available.
• @Inherited- marks the annotation to be inherited to subclasses.
• @Documented-Marks the annotation for inclusion in the documentation.
User Defined Annotations
 The programmer can construct own Annotations and use them.
 The @interface element is used to declare an annotation. For example:
@interface MyAnnotation
{ }
 Here, MyAnnotation is the user defined annotation name.
 Few important points about user defined annotation
• Method should not have any throws clauses
• Method should return one of the following: primitive data types, String, Class,
enum or array of these data types.
• Method should not have any parameter.
• We should attach @ just before interface keyword to define annotation.
• It may assign a default value to the method.
Types of Annotations
There are three types of annotations.
 Marker Annotation - An annotation that has no method, is called marker
annotation. For example: @interface MyAnnotation { }
 Single-Method Annotation - An annotation that has one method, is called single-
value annotation. For example:
@interface MyAnnotation
{
int value();
}
 Multi-Method Annotation -An annotation that has more than one method, is
called Multi-Value annotation. For example:
@interface MyAnnotation
{
int value1();
String value2();
String value3();
}
Example Program
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation //definition of annotation
{
int value();
}
//Applying annotation
class Hello
{
@MyAnnotation(value=10)
public void sayHello()
{
System.out.println("hello annotation");
}
}
//Accessing annotation

SACET, CSE Department, II CSE I SEM ( R23) Page 40


class TestCustomAnnotation1
{
public static void main(String args[])throws Exception
{
Hello h=new Hello();
Method m=h.getClass().getMethod("sayHello");
System.out.println("Method name is:"+m.getName());
MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
System.out.println("value is: "+manno.value());
}
}

SACET, CSE Department, II CSE I SEM ( R23) Page 41

You might also like