Unit -3 Java -R23
Unit -3 Java -R23
Unit - 3
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 Change of 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.
Introduction 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. The complete data gets represented by a single object with a single name in the computer
memory. An array is a sequence of objects of the same data type. The type of data that the array holds
becomes the type of the array, which is also called base type of the array. If the array elements have values
in whole numbers, that is, of type int, the type of array is also int. If it is a sequence of characters, the type
of array is char; If it is an array of floating point numbers of type float, the type of array is also float. An
array can hold objects of a class but cannot be a mixture of different data types.
Syntax:
datatype arrayName[]; or
type identifier[];
Examples:
Declaration of Array:
datatype arrayName[]; or
type identifier[];
Examples:
Initialization of Arrays:
An array may be initialized by mentioning the values in braces and separated by commas.
For example, the array pencils may be initialized as below:
int pencils [] = {4, 6, 8, 3};
• The first element space is represented by numbers [0], and index value is 0.
Note that the value of an array element is different from its index value.
Example:
Example-1:
class NumArray
{
public static void main(String args[])
{
int numbers[] = new int[4];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
for(int i =0 ;i<numbers.length; i++)
System.out.println(numbers[i]);
}
}
Output:
C:\>javac NumArray.java
C:\>java NumArray
10
20
30
40
class NumArray2
{
public static void main(String[] args)
{
int numbers [] = {20,10,30,50};
for(int i=0 ; i<numbers.length; i++ )
System.out.println(numbers[i]);
}
}
Output:
C:\>javac NumArray2.java
C:\>java NumArray2
10
20
30
40
}
}
Output:
C:\>javac NumArray3.java
C:\>java NumArray3
100
200
300
400
}
}
Output:
C:\>javac StringArray.java
C:\>java StringArray
Red
Blue
Green
Black
White
Example:
int[] array1 = new int []{1,2,3,4,5};
array1[0] = array1[0] + 10;
Here the value of the first element is added 10. Now its value is changed from 1 to 11.
Example: ArrayOperations.java
class ArrayOperations
{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
Output:
C:\>javac ArrayOperations.java
C:\>java ArrayOperations
Before Adding - Array elements are :
12345
After Adding - Array elements are :
11 12 13 14 15
• In this process, the second array identifier is the reference to the first array.
• The second array is not a new array, instead only a second reference is created.
• This is illustrated in this program, array1 is assigned to array2. Then, array1 is modified array2
also gets modified, which shows is not an independent array.
class ArrayAssignment
{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
int[] array2 = new int[array1.length];
Example:
class DyanamicArraySize
{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
Output:
C:\>javac DynamicArraySize.java
C:\>java DyanamicArraySize
Before Changing Array Size: array1 =
12345
After Changing Array Size: array1 =
0000000000
After Modification : array1 =
5 10 15 20 25 30 35 40 45 50
Sorting of Arrays
Sorting of arrays is often needed in many applications of arrays. For example, in the preparation of
“examination results” , “order of grades acquired by students” or “Student names in alphabetical order of
dictionary style”. The arrays may be sorted in ascending or descending order. Several methods are used for
sorting the arrays that include the following:
1. Bubble sort
2. Selection sort
3. Sorting by insertion method
Bubble Sort
This method of sorting is the simplest to understand but the most inefficient one; however, it can be use
fully employed for short arrays.
In the process, if the sorting is done in ascending order, the first element is compared with the second
element. If the value of the second is smaller than the first, the elements are inter changed, that is, the
second is made first and first is made second.
However, if the second is higher than the first, then no action is taken. The second element is then
compared with the third element and the aforementioned procedure is repeated. The third is then compared
with the fourth.
The process is repeated till the last . This process places the largest value as the last element. The process is
again element repeated for the next largest value from the remaining elements until the last element of the
array is reached. Thus, the process is repeated (n-1) times to completely sort the array.
Example:
class BubbleSort
{
public static void main(String args[])
{
int[] array1 = new int []{5,8,9,2,4,1,7,6};
// Buble Sorting
int t;
Selection Sort
Let us take an array with elements 9, 7, 4, 3, 6, and 8.
If the array is being sorted in ascending order, pick the element with the lowest value,
that is 3, and place at the first place as shown in the second line of Figure.
From the remaining elements that are 9, 7, 4, 6, 8, again pick the lowest value, that is, 4
and place it next to 3, as shown in the third line of the figure.
Then, from the remaining elements with values 9, 7, 6, 8, again pick the lowest value,
that is, 6 and place it next to 4.
From the remaining three values, 9, 7, 8, again pick the lowest value, that is, 7 and place
it next to 6 on its right side.
Then, from the remaining two values 9 and 8, pick the lowest, that is, 8 and place it next
to 7.
The highest value goes to the last place. The array is sorted with the lowest value at the
first place and the largest value at the end.
The process is better than the bubble sort but still not the most efficient.
Example:
class SelectionSort
{
static int min=0;
public static void main(String args[])
{
int[] array1 = new int []{9,7,4,3,6,7};
// Selection Sort
int minIndex=0;
Insertion Sort
• Sorting algorithm builds a final sorted array one item at a time.
• In this method, the value at any index is compared to all the prior elements.
• The input data is inserted into the correct position in the sorted list and the process is repeated until no
input element remains.
Example: InsertionSort.java
class InsertionSort
{
static int min=0;
public static void main(String args[])
{
int[] array1 = new int []{9,7,4,3,6,7};
// Insertion Sort
int len = array1.length;
SEAGI –NB-Department of CAI Page 13
OOPJ - R(23)
int i=0;
for(int j=1; j<len;j++)
{
key= array1[j];
i=j-1;
while(i>=0 && array1[i]>key)
{
array1[i+1] = array1[i];
i=i-1;
array1[i+1]=key;
}
/* System.out.println("\nAfter "+(i+1)+" Iteration
array1=");
display(array1);*/
}
Ouput:
C:\ >javac InsertionSort.java
C:\ >java InsertionSort
Before Sorting : array1 =
974367
After Sorting : array1 =
346779
Searching an array for a value is often needed. Let us consider the example of searching for
your name among the reserved seats in a rail reservation chart, etc. Two methods are used in
1. Linear search
Linear search
Example:
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
boolean b =false;
int[] array = {67,78,85,44,25,65,36};
Scanner in = new Scanner(System.in);
System.out.println("Enter the number which you want to
search");
int key = in.nextInt();
for(int i=0; i<array.length; i++)
{
if(array[i] == key)
{
System.out.println("Your number is at index = " + i);
b=true;
}
}
if(b!=true)
System.out.println("Your number is not in the array");
}
}
SEAGI –NB-Department of CAI Page 15
OOPJ - R(23)
Output:
C:\>javac LinearSearch.java
C:\>java LinearSearch
Enter the number which you want to search
44
Your number is at index = 3
C:\>java LinearSearch
Enter the number which you want to search
65
Your number is at index = 5
C:\>java LinearSearch
Enter the number which you want to search
888
Your number is not in the array
It is a very efficient method of search but it is applicable only to the sorted arrays.
The beginning, end, and the midpoint of the array are defined first.
If it does not match, then it is checked in which half of the array the key value lies by checking
whether the key value is more or less than the value at midpoint.
The array is truncated to the half in which the key value lies.
This process is repeated on that half, that is, it is again divided into two halves where the value is
compared with the midpoint;
if match is not found, it is determined in which half of the truncated array the value lies.
Example:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
boolean b =false;
int[] array = {15, 20, 43, 45, 76, 80, 86, 88, 90, 94, 96,
98};
int length= array.length;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number which you want to
search");
int key = in.nextInt();
int beginning,end,mid;
beginning =0;
end = length-1;
while( beginning <=end)
{
if(beginning == end && array[end]!=key)
{
System.out.println("Your number is not in the array");
break;
}
mid = (beginning +end )/2;
if(array[mid]==key)
{
System.out.println("Your number is in the array at index =
" + mid);
SEAGI –NB-Department of CAI Page 17
OOPJ - R(23)
break;
}
else if(array[mid]<key)
beginning = mid+1;
else
end = mid-1;
}
}}
Output:
C:\>javac BinarySearch.java
C:\>java BinarySearch
Enter the number which you want to search
45
Your number is in the array at index = 3
C:\>java BinarySearch
Enter the number which you want to search
96
Your number is in the array at index = 10
C:\>java BinarySearch
Enter the number which you want to search
783
Your number is not in the array
Class Arrays
The package java.util defines the class Arrays with static methods. –
• for general processes that are carried out on arrays such as sorting an array for full length of the
array or for part of an array, binary search of an array for the full array or part of an array,
• for filling a part or the full array with elements having a specified value.
• The methods are applicable to all primitive types as well as to class objects.
Sort
• The class defines several overloaded methods for sorting arrays of different types.
Example: PredefinedMethodSort.java
import java.util.Arrays;
class PredefinedMethodSort
{
public static void main(String args[])
{
int[] array1 = new int []{41,4,31,14,5};
System.out.println("Array-1 elements are :");
display(array1);
System.out.println();
//Predefined Method Sort of Arrays class
Arrays.sort(array1);
System.out.println("After Sort, Array-1 elements are :");
display(array1);
System.out.println();
}
static void display(int[] array) //Method definition
{
for (int x : array)
System.out.print(x + " ");
}
}
Output:
C:\>javac PredefinedMethodSort.java
C:\ >java PredefinedMethodSort
Array-1 elements are :
41 4 31 14 5
After Sort, Array-1 elements are :
4 5 14 31 41
Searching
There are two versions of overloaded binary Search method that are
defined in class Arrays.
1. public static int binarySearch(int [] array, int key)
Equals
public static boolean equals (int [] a, int [] b)
The output is a Boolean value—it returns true, if the elements and their order in the two arrays are
same; otherwise, it returns false.
Fill
The two versions of method fill defined in class Arrays are as follows.
2. public static void fill(byte [] array, int startIndex, int endIndex, byte value)
The method fills the specified subset of an array with the specified value
CopyOf
The method copies the array into a new array of specified length
2. copyOfRange
public static char [] copyOfRange( char [] original, int fromIndex, int toIndex)
asList
toString
The method header is given as public static String toString (int [] array)
Two-dimensional Arrays
If the elements of an array are one-dimensional arrays, the array becomes a two-dimensional array.
A two-dimensional array is treated as an array of arrays, and each of these arrays may have a
different number of elements.
Example: TwoDimArray.java
class TwoDimArray
{
public static void main(String[] args)
{
int num2D[][]= {{1,2,3},{4,5,6},{7,8,9}};
for(int[] y : num2D)
{
for(int x : y)
System.out.print( x + " ");
System.out.println();
}
}
}
Output:
C:\ >javac TwoDimArray.java
C:\ >java TwoDimArray
123
456
789
Example: TwoDimArray2.java
class TwoDimArray2
{
public static void main(String[] args)
{
int num2D[][]= {{5,7,8},{10,11},{4,3,2,7,5}};
for(int[] y : num2D)
{
for(int x : y)
System.out.print( x + " ");
System.out.println();
}
}
}
C:\>javac TwoDimArray2.java
C:\>java TwoDimArray2
578
10 11
43275
Three-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.
Example: ThreeDimArray.java
class ThreeDimArray
{
public static void main(String[] args)
{
int num3D[][][]= { { {1,2,3}, {4,5,6}, {7,8,9} },
{ {11,12,13},{14,15,16},{17,18,19} }
};
for(int[][] z: num3D)
{
for(int[]y : z)
{
for(int x : y)
System.out.print( x + " ");
System.out.println();
}
System.out.println();
}
}
}
Output:
C:\1. JAVA\UNIT-3.1>javac ThreeDimArray.java
C:\1. JAVA\UNIT-3.1>java ThreeDimArray
123
456
789
11 12 13
14 15 16
17 18 19
Arrays as Vectors.
• Similar to Arrays, vectors are another kind of data structure that is used for storing
information.
• Using vector, we can implement a dynamic array.
• The following are the vector constructors:
• Vector() creates a default vector having an initial size of 10.
• Vector(int size) creates a vector whose initial capacity is specified by size.
Example
Vector vec = new Vector(5); // declaring with initial size of 5
• Vector(int size, int incr) creates a vector with initial capacity specified by size and
increment is specified by incr.
• The increment is the number of elements added in each reallocation cycle.
Advantages of Vectors.
Vectors have a number of advantages over arrays.
i. Vectors are dynamically allocated, and therefore, they provide efficient memory
allocation.
ii. Size of the vector can be changed as and when required.
iii. They can store dynamic list of objects.
iv. The objects can be added or deleted from the list as per the requirement.
Example: VetorArray.java
import java.util.*;
class VectorArray
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Vector capacity : ");
int n = in.nextInt();
Output:
C:\>javac VectorArray.java
C:\>java VectorArray
Enter the Vector capacity :
7
Intial size of Vector0
Intial capacity of Vector7
Current size of Vector7
Intial capacity of Vector7
Vector Elements are
10 11 12 13 14 15 16
Vector Elements after removing element at index 3
10 1 12 14 15 16
Inheritance:
Introduction
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.
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.
Benefits of Inheritance
• It allows the reuse of already developed and debugged class program without any modification.
• A large program may be divided into suitable classes and subclasses that may be developed by separate
teams of programmers.
Disadvantages of Inheritance
1. The tight coupling between super and subclasses increases and it becomes very difficult to use them
independently.
2. Program processing time increases as it takes more time for the control to jump through various levels of
overloaded classes.
3. When some new features are added to super and derived classes as a part of maintenance, the changes
affect both the classes.
4. 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.
Process of Inheritance
In the context of Java, it implies deriving a new class from an existing old class, that is, the super
class.
Either, make a separate class for the subset to include all the characteristics or, to have another class
that inherits the existing class, extend this class to include the special characteristics.
Types of Inheritances
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
i) Single inheritance: It is the simple type of inheritance. In this, a class extends another one class only.
Example: SingleInheritance.java
class DemoA
{
void displayA()
{
System.out.println("Super Class Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Sub Class Method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
DemoA objA = new DemoA();
objA.displayA();
DemoB objB = new DemoB();
objB.displayB();
}
}
Output:
C:\>javac SingleInheritance.java
C:\>java SingleInheritance
Super Class Method
Sub Class Method
ii) Multilevel inheritance: In this type, a derived class inherits a parent or super class; The derived class also acts as
the parent class to other class
Example: Multilevel.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Class-B Method");
}
}
class DemoC extends DemoB
{
void displayC()
{
System.out.println("Class-C Method");
}
}
class Multilevel
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
//calling class-B method
DemoB objB = new DemoB();
objB.displayB();
//calling class-C method
DemoC objC = new DemoC();
objC.displayC();
}
}
Output:
C:\>javac Multilevel.java
C:\>java Multilevel
Class-A Method
Class-B Method
Class-C Method
iii) Hierarchical inheritance: In this type, one class is inherited by many sub classes.
Example: Hierarchical.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Class-B Method");
}
}
class DemoC extends DemoA
{
void displayC()
{
System.out.println("Class-C Method");
}
}
class Heirarchical
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
iv) Multiple inheritance: In this, a class is extending more than one class.
Java does not support multiple inheritance.
This implies that a class cannot extend more than one class.
Suppose there is a method in class A. This method is overridden in class B and class C in their own
way.
Since class C extends both the classes A and B.
So, if class C uses the same method, then there will be ambiguity as which method is called.
Example: Multiple.java
interface X
{
int x=10;
SEAGI –NB-Department of CAI Page 31
OOPJ - R(23)
}
interface Y
{
int y=20;
}
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class DemoB extends DemoA implements X,Y
{
void displayB()
{
System.out.println("Class-B Method : x+y = " +
(x+y));
}
}
class Multiple
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();
Example:ObjectEquals.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class ObjectEquals
{
public static void main(String args[])
{
DemoA obj1 = new DemoA();
DemoA obj2 = new DemoA();
boolean test;
//Checking - if both object are equal
test = obj1.equals(obj2);
display(test);
// Object assignment
obj1=obj2;
Class variables or instance variables are declared as constant to make local variables.
In order to prevent the methods from being overridden, that method can be declared as final.
Example:FinalClass.java
final class A
{
int a;
A(int x) {a=x;}
void display()
{
System.out.println("a = "+ a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);
this.b=y;
}
void display()
{
System.out.println("b = "+ b);
}
}
class FinalClass
{
public static void main (String args[])
{
A objA= new A(10);
B objB= new B(100,200);
objA.display();
objB.display();
}
}
Output:
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final A
class B extends A
^
1 error
Example-1: DefaultAccess.java
class DemoA
{
int a;
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
void displayB()
{
System.out.println("Class-B Method : a = " + a + " b = " + b );
}
}
class DefaultAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.a=100; // accessing all classes in the same package
objA.displayA();
}
}
Output:
C:\>javac DefaultAccess.java
C:\>java DefaultAccess
Class-A Method : a = 100
Class-B Method : a = 200 b = 300
Multilevel Inheritance
In this type, a derived class inherits a parent or super class;
• The derived class also acts as the parent class to other class.
• First, to distinguish between the variables having the same name in super class and
subclass.
• When the member is called with an object of subclass, the subclass value will be presented and
super class value will get hidden.
Instead of repeating the assignment of variables of super class, we simply qualify the variable
with super.
Example: SuperDemo.java
class A
{
int a;
A(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class B extends A
{
int b;
B(int p, int q)
{
super(p); // Calling Super class Construtor
b=q;
}
void displayB()
{
// Refering Super class with super keyword
System.out.println("Class-B Method : a = " + super.a + " b = " + b );
}
}
class SuperDemo
{
public static void main(String args[])
{
//Creating class B object by calling sub class constructor
B objB = new B(500,1000);
}
}
Output:
C:\>javac SuperDemo.java
C:\>java SuperDemo
Class-B Method : a = 500 b = 1000
Method Overriding
It is one of the ways in which polymorphism can be implemented.
When both super class and its subclass contain a method that has the same name and type signature,
the super class definition of the method is overridden by definitions in subclass.
It is different from the overloaded method in which only the name is same but parameter list has to
be different either in type or in number of parameters or order of parameters.
In the case of overloaded methods, the parameter lists are matched to choose the appropriate
method that may be in super class or subclass.
When two methods with the same name and type signature are defined in super (base) class as well
as in subclass (derived class), the subclass definition overrides the super class definition when the
method is called by object of subclass;
It will execute the method defined in subclass and hide the definition of super class.
Binding
• It involves associating the method call to method body. There are two types of binding as follows:
Static binding : When the binding is performed at compile time by the compiler, it is known as static or
early binding.
• For instance, binding for all static, private, and final methods is done at the compile time.
Dynamic binding : It is also called late binding. Here, the compiler is not able to resolve the call (or
binding) at compile time.
• Method overriding is one such example where dynamic binding is involved.
• The basic difference between static and dynamic binding is that static binding occurs at compile time,
whereas dynamic binding happens at run time.
Example: MethodOverriding.java
class A
{
void display()
{
System.out.println("Super Class Method");
}
}
class B extends A
{
void display()
{
System.out.println("Sub Class Method");
}
}
class MethodOverriding
{
public static void main(String args[])
{
//calling the class A method
A objA = new A();
objA.display();
//calling the class B method
objA = new B();
objA.display();
}
}
Output:
C:\>javac MethodOverriding.java
C:\>java MethodOverriding
Super Class Method
Sub Class Method
Abstract Classes
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
Example: Abstract.java
abstract class A
{
int a;
void setValue(int x)
{
a=x;
}
abstract void display();
}
class B extends A
{
int b;
void setValues(int x, int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " b = " + b);
}
}
class C extends A
{
int c;
void setValues(int x, int y)
{
a=x;
c=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " c = " + c);
}
}
class Abstract
{
public static void main(String args[])
{
//calling class-B method
System.out.println("Through objB");
B objB = new B();
objB.setValues(10,20);
objB.display();
//calling class-C method
System.out.println("Through objC");
C objC = new C();
SEAGI –NB-Department of CAI Page 43
OOPJ - R(23)
objC.setValues(150,250);
objC.display();
}
}
Interfaces:
Introduction
https://www.w3schools.com/java/java_interface.asp An interface is a completely
"abstract class" that is used to group related methods with empty bodies
https://www.javatpoint.com/interface-in-java An interface in Java is a blueprint of a
class. It has static constants and abstract methods.
https://www.geeksforgeeks.org/interfaces-in-java/ Like a class, an interface can have
methods and variables, but the methods declared in an interface are by default
abstract (only method signature, no body).
• An interface also introduces a new reference type.
An interface represents an encapsulation of constants, classes, interfaces, and one or
more abstract methods that are implemented by a class.
• An interface does not contain instance variables.
• An interface cannot implement itself; it has to be implemented by a class.
• The methods in an interface have no body.
SEAGI –NB-Department of CAI Page 44
OOPJ - R(23)
• Only headers are declared with the parameter list that is followed by a semicolon.
The class that implements the interface has to have full definitions of all the abstract
methods in the interface.
An interface can be implemented by any number of classes with their own definitions
of the methods of the interface.
Different classes can have different definitions of the same methods but the
parameter list must be identical to that in the interface.
Thus, interfaces provide another way of dynamic polymorphic implementation of
methods.
• Any number of interfaces can be implemented by a class.
• This fulfils the need for multiple inheritance.
The multiple inheritances of classes are not allowed in Java, and therefore, interfaces
provide a stopgap arrangement.
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.
• 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
Types of Interfaces
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.
Nested interface
• It is an interface that is defi ned 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.
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.
Declaration of Interface
• Declaration of an interface starts with the access modifier followed by keyword
interface.
• It is in then 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 by default.
Members of Interface
• The methods declared in the interface are implicitly public abstract member
methods.
• The field variables defined in interfaces are implicitly public, static, and final.
• However, the specification of these modifiers does not create a compile-type error.
• Since Java SE8, static and default methods with full definition can also be members
of interface.
Implementation of Interface
Multiple Interfaces
Interface 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.
Example: InterfaceRef.java
interface X
{
int x = 10;
public void display();
}
interface Y
{
int y = 20;
public void add();
}
class A implements X,Y
{
public void display()
{
System.out.println("Class-B Method : x = "+ x + " y = " + y);
SEAGI –NB-Department of CAI Page 48
OOPJ - R(23)
}
public void add()
{
System.out.println("Class-B Method : x+y = "+ (x+y));
}
}
class InterfaceRef
{
public static void main(String args[])
{
//Reference of X
X objX = new A();
objX.display();
//Reference of Y
Y objY = new A();
objY.add();
}
}
Output:
C:\ >javac InterfaceRef.java
C:\ >java InterfaceRef
Class-B Method : x = 10 y = 20
Class-B Method : x+y = 30
Nested Interfaces
Inheritance of Interfaces
Syntax:
access_specifier interface NewInterface extends OldInterface
{
//Body of the interface
}
Example:
interface A{}
interface B{}
interface C extends A,B
{
//Body of the interface
}
• The enhancement in Java 8 allowing the interface to have full definition of default
methods and static methods that are implicitly inherited by the class implementing the
interface.
• Java allows only one super class, by using default methods in interface java allows that
interface behaves just like an abstract super-class.
• New functionality can be added to the interface, which is inherited by classes
implementing the interface.
• The inherited methods are also members of the class, and therefore, these maybe called
other methods of class.
• A default method cannot be declared final.
• A default method cannot be synchronized; however, blocks of statements in the default
method may be synchronized.
• The object class is inherited by all classes. Therefore, a default method should not
override any non- final method of object class.
Example: StaticMethods.java
interface X
{
int x = 10;
static void display()
{
System.out.println("Method in Interface X the value x
= " + x);
}
}
class StaticMethods
{
public static void main(String args[])
{
//calling static method by specifying interface X
X.display();
}
}
Output:
C:\>javac StaticMethods.java
C:\>java StaticMethods
Method in Interface X the value x = 10
Functional Interfaces
• In Java SE8, a new package java.util.function on functional interfaces has been introduced
for writing Lambda functions.
• 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.
• The programmer may include an annotation, to lessen the work of complier.
@FunctionalInterface
• By adding the above annotation, it can be helpful in detecting compile time errors.
• If the functional interface contains more than one abstract method, the compiler will throw
an error.
Functional Consumer<T>
• The interface declaration is
@FunctionalInterface
public interface Consumer {void accept(T t);}
• It declares one abstract method void accept(T t).
• The method only consumes its argument. It does not give any return value.
Annotations.
Unit - 4