0% found this document useful (0 votes)
2 views35 pages

Java Unit 3

This document covers Unit III on Arrays, Inheritance, and Interfaces in Java programming. It provides detailed explanations on array declaration, initialization, operations, and sorting methods, as well as concepts of inheritance and interfaces. Key topics include dynamic array size changes, method parameters, and various sorting techniques using built-in Java methods.

Uploaded by

buppalaiah.svist
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)
2 views35 pages

Java Unit 3

This document covers Unit III on Arrays, Inheritance, and Interfaces in Java programming. It provides detailed explanations on array declaration, initialization, operations, and sorting methods, as well as concepts of inheritance and interfaces. Key topics include dynamic array size changes, method parameters, and various sorting techniques using built-in Java methods.

Uploaded by

buppalaiah.svist
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/ 35

UNIT III

ARRAYS, INHERITANCE & INTERFACES


3.1 ARRAYS:
3.1.1 Introduction
3.1.2 Declaration and Initialization of Arrays
3.1.3 Storage of Array in Computer Memory
3.1.4 Accessing Elements of Arrays
3.1.5 Operations on Array Elements
3.1.6 Assigning Array to Another Array
3.1.7 Dynamic Change of Array Size
3.1.8 Sorting of Arrays
3.1.9 Search for Values in Arrays
3.1.10 Class Arrays
3.1.11 Two-dimensional Arrays
3.1.12 Arrays of Varying Lengths
3.1.13 Three-dimensional Arrays
3.1.14 Arrays as Vectors.

3.2 INHERITANCE:
3.2.1 Introduction
3.2.2 Process of Inheritance
3.2.3 Types of Inheritances
3.2.4 Universal Super Class- Object Class
3.2.5 Inhibiting Inheritance of Class Using Final
3.2.6 Access Control and Inheritance
3.2.7 Multilevel Inheritance
3.2.8 Application of Keyword Super
3.2.9 Constructor Method and Inheritance
3.2.10 Method Overriding
3.2.11 Dynamic Method Dispatch
3.2.12 Abstract Classes
3.2.13 Interfaces and Inheritance.

3.3 INTERFACES:
3.3.1 Introduction
3.3.2 Declaration of Interface
3.3.3 Implementation of Interface
3.3.4 Multiple Interfaces
3.3.5 Nested Interfaces
3.3.6 Inheritance of Interfaces
3.3.7 Default Methods in Interfaces
3.3.8 Static Methods in Interface
3.3.9 Functional Interfaces
3.3.10 Annotations

JAVA PROGRAMMING 1 KKVPRASAD@CSE


3.1.1 INTRODUCTION: ARRAYS
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

ADVANTAGES
 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
DISADVANTAGES
 Size Limit: We can store only the fixed size of elements in the array.
 It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
TYPES OF ARRAY IN JAVA
 There are two types of array.
 Single Dimensional Array
 Multidimensional Array

3.1.2 DECLARATION AND INITIALIZATION OF ARRAYS


Declaration of an Array
The syntax of declaring an array in Java is given below.
datatype [] arrayName;
Here, the datatype is the type of element that will be stored in the array, square bracket[] is for the
size of the array, and arrayName is the name of the array.

Initialization of an Array
Only the declaration of the array is not sufficient. In order to store values in the array, it is required to
initialize it after declaration. The syntax of initializing an array is given below.
datatype [] arrayName = new datatype [ size ]

1. Without assigning values


In this way, we pass the size to the square braces[], and the default value of each element present in
the array is 0. Let's take an example and understand how we initialize an array without assigning values.

ArrayExample1.java
public class ArrayExample1 {
public static void main( String args[] ) {
//initializing array without passing values
JAVA PROGRAMMING 2 KKVPRASAD@CSE
int[] array = new int[5];
//print each element of the array
for (int i = 0; i < 5; i++)
{
System.out.println(array[i]);
}} }
Output:

2. Initialize and assign values together


In this way, we declare and initialize the array together. We don't do both the declaration and
initialization separately. Let's take an example and understand how we do both the thing together:

ArrayExample3.java
public class ArrayExample3 {
public static void main( String args[] ) {
int [] numbers = {22,33,44,55,66};
for (int i = 0; i < 5; i++)
{
System.out.println(numbers[i]);
}}}
Output:

3.1.3 STORAGE OF ARRAY IN COMPUTER MEMORY


The operator new allocates memory for storing the array elements.
int [] numbers = new int [4];
here 4 elements will be created and assigned to the array “numbers”
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}};

3.1.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.
• Note that the value of an array element is different from its index value.
Example:
int numbers [] = {20,10,30,50};

JAVA PROGRAMMING 3 KKVPRASAD@CSE


Here
number[0] is the first element
number[1] is the second element
number[2] is the third element and so on…
value at number[0] is 20,
value at number[1] is 10,
value at number[2] is 30,
value at number[3] is 50.

Determination of Array Size

 The size or length of an array may be determined using the following code:
int arraySize = array_identifier.length;
 The size of array numbers is determined as:
int size = numbers.length;
 The elements of a large array may be accessed using a for loop.
 For example, the elements of array numbers may be accessed as
for (int i = 0; i<size; i++)
System.out.println(x);
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:
10
20
30
40

3.1.5 OPERATIONS ON ARRAY ELEMENTS


Arithmetic Operations on Arrays:

Arithmetic operations can be applied on Array elements.


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 1to 11.

JAVA PROGRAMMING 4 KKVPRASAD@CSE


Arrays as Parameters of Methods:

Arrays can be passed to methods just like variables.


Example:
display(array1); // Method calling
. . . . ..
void display(int[] array) //Method definition
{
for (int x : array) System.out.println(x + “ ”);
}

Example: ArrayOperations.java

class ArrayOperations
{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
System.out.println("Before Adding - Array elements are :"); display(array1);
//Passing an array to display() methodSystem.out.println();
// Operations on Arrays
for(int i =0; i< array1.length; i++)
array1[i] = array1[i] + 10; // Adding 10 to each element
System.out.println("After Adding - Array elements are :");
display(array1);
}
static void display(int[] array) //Method definition
{
for (int x : array) System.out.print(x + " ");
}}
Output:
Before Adding - Array elements are:
12 3 4 5
After Adding - Array elements are:
11 12 13 14 15

3.1.6 ASSIGNING ARRAY TO ANOTHER ARRAY

 In Java, an array may be assigned to another array of same data type.


 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 modifiedarray2 also gets modified, which shows is not an independent array.
Example:
class ArrayAssignment{
public static void main(String args[]){
int[] array1 = new int []{1,2,3,4,5};
int[] array2 = new int[array1.length];
System.out.println("Array-1 elements are :");
display(array1);
System.out.println();

JAVA PROGRAMMING 5 KKVPRASAD@CSE


array2 = array1; // Array Assignment
System.out.println("Array-2 elements are :");
display(array2); // Method calling System.out.println();
//Modification of array2 elements
for(int i=0;i<array2.length;i++)
array2[i]+=100; //adding 100 to each element of array2
System.out.println("After Modification of Array2 \n Array-1elements are :");
display(array1);
System.out.println();
}
static void display(int[] array) //Method definition
{
for (int x : array) System.out.print(x + " ");
}}
Output:
Array-1 elements are :
1 2 3 4 5
Array-2 elements are :
1 2 3 4 5
After Modification of Array2
Array-1 elements are :
101 102 103 104 105

3.1.7 DYNAMIC CHANGE OF ARRAY SIZE


Java allows us to change the array size dynamically during the execution of the program. In this
process the array destroyed along with the values of elements. In the following program, the array
contains 5 elements. It is again defined with 10 elements with the same array name.
Example:
class DyanamicArraySize{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
System.out.println("Before Changing Array Size: array1 = ");
display(array1);
array1 = new int[10]; //Changing array size
System.out.println("\nAfter Changing Array Size: array1 = ");
display(array1);
for(int i=0;i<10;i++)
array1[i] = 5*(i+1);
System.out.println("\nAfter Modification : array1 = ");

display(array1);
}
static void display(int[] array) //Method definition
{
for (int x : array)
System.out.print(x + " ");
}}
Output:
Before Changing Array Size: array1 =1 2 3 4 5
After Changing Array Size: array1 = 0 0 0 0 0 0 0 0 0
After Modification : array1 = 5 10 15 20 25 30 35 40 45 50
JAVA PROGRAMMING 6 KKVPRASAD@CSE
3.1.8 SORTING OF ARRAYS
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion
sort, radix sort, bucket sort, etc but if we look closer here, we are not asked to use any kind of algorithms. It
is as simple sorting with the help of linear and non-linear data structures present within java. So there is
sorting done with the help of brute force in java with the help of loops and there are two in-built methods to
sort in Java.

Ways of sorting in Java


1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
1: Using loops
class Techno {
// Main driver method
public static void main(String[] args)
{
// Custom input array
int arr[] = { 4, 3, 2, 1 };
// Outer loop
for (int i = 0; i < arr.length; i++) {
// Inner nested loop pointing 1 index ahead
for (int j = i + 1; j < arr.length; j++) {
// Checking elements
int temp = 0;
if (arr[j] < arr[i]) {
// Swapping
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
} }
System.out.print(arr[i] + " ");
}
}}
Output:
1234

2: Using sort() method of Arrays class


Arrays.Sort() works for arrays which can be of primitive data type also which in turn by default sorts
in ascending order.
import java.util.Arrays;
public class Techno {
public static void main(String[] args)
{
int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s", Arrays.toString(arr));
}
}
Output
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

JAVA PROGRAMMING 7 KKVPRASAD@CSE


3: Using sort() method of Collections class
Collections.sort() works for objects Collections like ArrayList and LinkedList.
// Java program to demonstrate working of Collections.sort()
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("Techno");
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
/* Collections.sort method is sorting the
elements of ArrayList in ascending order. */
Collections.sort(al);
System.out.println("List after the use of" + " Collection.sort() :\n" + al);
}
}
Output
List after the use of Collection.sort() :
[Dear, Friends, Techno, Is, Superb]

Way 4: Sorting only a subarray


import java.util.Arrays;
public class Techno
{
public static void main(String[] args)
{
int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
Arrays.sort(arr, 1, 5);
// Printing sorted array
System.out.printf("Modified arr[] : %s",Arrays.toString(arr));
}
}
Output
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]

3.1.9 SEARCH FOR VALUES IN ARRAYS


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 insearching, They are :
1. Linear search
2. Binary search for sorted arrays

1. Linear search
 The method may be applied to any array.
 The key value is compared to the value of the elements of the array successively.If a
match is found, it is noted, and the program ends there.
 Otherwise, the complete array is searched, and if no match is found, it is reported that thevalue is
not there in the array.
public class LinearSearchExample{
JAVA PROGRAMMING 8 KKVPRASAD@CSE
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
} } return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:
50 is found at index: 3

2. Binary search for sorted arrays.

 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.
 The key value is compared with the value at midpoint.
 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 thevalue is
compared with the midpoint;
 if match is not found, it is determined in which half of the truncated array the value lies.

class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}}
Output:
Element is found at index: 2
JAVA PROGRAMMING 9 KKVPRASAD@CSE
3.1.10 CLASS ARRAYS
 The Arrays class in java.util package is a part of the Java Collection Framework.
 This class provides static methods to dynamically create and access Java arrays. It consists of only
static methods and the methods of Object class.
 The methods of this class can be used by the class name itself.
 The class hierarchy is as follows:
java.lang.Object
↳ java.util.Arrays
Some of the methods in Class Arrays
1: asList() Method
2: binarySearch() Method
3: binarySearch(array, fromIndex, toIndex, key, Comparator) Method
4: compare(array 1, array 2) Method
5: compareUnsigned(array 1, array 2) Method
6: copyOf(originalArray, newLength) Method
7: copyOfRange(originalArray, fromIndex, endIndex) Method
8: deepEquals(Object[] a1, Object[] a2) Method
9: equals(array1, array2) Method
10: mismatch(array1, array2) Method
11: sort(originalArray) Method
12: sort(originalArray, fromIndex, endIndex) Method

3.1.11 TWO-DIMENSIONAL ARRAYS

 An array may hold other arrays as its elements.


 If the elements of an array are one-dimensional arrays, the array becomes atwo-
dimensional array.
 A two-dimensional array is treated as an array of arrays, and each of thesearrays may
have a different number of elements.
 E.g. Matrices are two-dimensional arrays.
 A two-dimensional array may be defined as:
int telNumber [][] = new int [5][10];
 The array will contain 5 numbers each having 10 digits.
 A two-dimensional array may as well be defined and initialized as
int arrayB [ ][ ] = {{11, 12, 13 }, {7, 6, 4}};
 The two-dimensional array may as well be declared as
int arrayC [][] = new int[2][3]{{1,2,3}. {4.5.6},{7,8,9}}

3.1.12 ARRAYS OF VARYING LENGTHS

 A two-dimensional array is treated as an array whose elements are one-dimensional


arrays, which may have different sizes.
 A two-dimensional array may be declared as
int a2D [][] = new int [3 ][];
 The arrays may as well be declared as
int array [][] = {{5, 7, 8 },{10, 11 }, {4, 3, 2, 7,5 }};

JAVA PROGRAMMING 10 KKVPRASAD@CSE


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();
}
}}
Output:
TwoDimArray25 7 8
10 11
43275

3.1.13 THREE-DIMENSIONAL ARRAYS


 When an array holds two-dimensional arrays as its elements, the array is a three-dimensional array.
 A practical example includes an array of matrices.
 Each basic element of such an array needs three index values for its reference.
 A three-dimensional array may be declared as
int tDArray [][][]; //Declaration
double d3Array [][][]; //Declaration

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:
123
456
789
11 12 13
14 15 16
17 18 19

JAVA PROGRAMMING 11 KKVPRASAD@CSE


3.1.14 ARRAYS AS VECTORS
 Similar to Arrays, vectors are another kind of data structure that is used for storinginformation.
 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.
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 andincrement is
specified by incr.
 The increment is the number of elements added in each reallocation cycle.

Advantages of Vectors.

 Vectors are dynamically allocated, and therefore, they provide efficient memoryallocation.
 Size of the vector can be changed as and when required.
 They can store dynamic list of objects.
 The objects can be added or deleted from the list as per the requirement.

JAVA PROGRAMMING 12 KKVPRASAD@CSE


3.2.1 INTRODUCTION : INHERITANCE

 Inheritance is the backbone of object-oriented programming (OOP).


 It is the mechanism by which a class can acquire properties and methods of anotherclass.
 Using inheritance, an already tested and debugged class program can be reused forsome
other application.
 Super class This is the existing class from which another class, that is, the subclass isgenerally
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.

Benefits of Inheritance
 It allows the reuse of already developed and debugged class program without any
modification.
 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 bedeveloped by
separate teams of programmers.

Disadvantages of Inheritance
 The tight coupling between super and subclasses increases and it becomes very difficultto use
them independently.
 Program processing time increases as it takes more time for the control to jumpthrough
various levels of overloaded classes.
 When some new features are added to super and derived classes as a part ofmaintenance, 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.

3.2.2 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.Either, make a separate class for the subset
to include all the characteristics or, to haveanother class that inherits the existing class, extend
this class to include the special characteristics.

JAVA PROGRAMMING 13 KKVPRASAD@CSE


TYPES OF INHERITANCES
The following types of inheritances are supported by Java.
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance using interfaces

1. Single inheritance: It is the simple type of inheritance. In this, a class extendsanother


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:
SingleInheritance
Super Class MethodSub Class Method

JAVA PROGRAMMING 14 KKVPRASAD@CSE


2. 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:
Method Class-B Method Class-C Method

3. Hierarchical inheritance: In this type, one class is inherited by many sub classes.

JAVA PROGRAMMING 15 KKVPRASAD@CSE


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();
DemoB objB = new DemoB();objB.displayB();
DemoC objC = new DemoC();
objC.displayC();
}
}

Output:

C:\ >javac Hierarchical.java


C:\ >java HierarchicalClass-A Method
Class-B MethodClass-C Method
4. 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 iscalled.

JAVA PROGRAMMING 16 KKVPRASAD@CSE


Example: Multiple.java

interface X
{
int x=10;
}
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[])
{
DemoA objA = new DemoA();objA.displayA();
DemoB objB = new DemoB();objB.displayB();
}
}

Output:
Class-A Method
Class-B MethodClass-C Method

JAVA PROGRAMMING 17 KKVPRASAD@CSE


3.2.3 UNIVERSAL SUPER CLASS- OBJECT CLASS
 Object class is a special class and it is at the top of the class hierarchy tree.
 It is the parent class or super class of all in Java.
 Hence, it is called Universal super class.
 Object is at the root of the tree and every other class can be directly or indirectly
derived from the Object class.

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;
//Checking - if both object are equal after assigning theobjects
test = obj1.equals(obj2);
display(test);
}
public static void display(boolean test)
{

JAVA PROGRAMMING 18 KKVPRASAD@CSE


if (test)
System.out.println("Both objects are same"); else
System.out.println("Both objects are different");
}
}

Output:
Both objects are different
Both objects are same

3.2.4 INHIBITING INHERITANCE OF CLASS USING FINAL

 A class declared as final cannot be inherited further.


 Class variables or instance variables are declared as constant to make local
variables.
 When a class is inherited by other classes, its methods can be overridden.
 In order to prevent the methods from being overridden, that method can bedeclared
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:
JAVA PROGRAMMING 19 KKVPRASAD@CSE
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final Aclass B extends A
^
1 error

3.2.5 ACCESS CONTROL AND INHERITANCE


 A derived class access to the members of a super class may be modified byaccess
specifiers.
 There are three access specifiers, that is, public, protected, and private.
 The code for specifying access is Access-specifier type member_identifier;

Example-1: DefaultAccess.javaclass
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[])

JAVA PROGRAMMING 20 KKVPRASAD@CSE


{
//calling class-A method
DemoA objA = new DemoA();
objA.a=100; // accessing all classes in the same packageobjA.displayA();
//calling class-B method
DemoB objB = new DemoB();
objB.a=200; // objA and objB are different objects. a isassigned with 200
objB.b=300; // accessing all classes in the same packageobjB.displayB();

}
}

Output:
C:\>javac DefaultAccess.java
C:\>java DefaultAccess
Class-A Method : a = 100
Class-B Method : a = 200 b = 300

Example -2: PrivateAccess.java

class DemoA
{
private int a;DemoA(int
x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
DemoB(int p, int q)
{
super(p);b=q;
}
void displayB()
{
displayA();
System.out.println("Class-B Method : b = " + b );
}
}
class PrivateAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(150);
//objA.a=100; // Error, Can't access private variable
objA.displayA();
//calling class-B method

JAVA PROGRAMMING 21 KKVPRASAD@CSE


DemoB objB = new DemoB(500,1000);
// objB.a=200; // objA and objB are different objects. Error,Can't access private variable
//objB.b=300; // accessing all classes in the same package
objB.displayB();
}
}
Output:
Class-A Method : a = 150 Class-A Method : a = 500 Class-B Method : b = 1000

Example: ProtectedAccess.java

class DemoA
{
protected int a;DemoA(int t)
{
a = t;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
DemoB(int p, int q)
{
super(p);b=q;
}
void displayB()
{
System.out.println("Class-B Method : a= " + a + " b = " + b );
}
}
class DemoC extends DemoB
{
int c;
DemoC(int x, int y, int z)
{
super(x,y);c=z;
}
void displayC()
{
System.out.println("Class-B Method : a = " + a + " b = " + b +" c = " + c);
}
}
class ProtectedAccess
{
public static void main(String args[])
{
//calling class-A method DemoA objA = new
DemoA(100);
//objA.a=100; // Error, Can't access protected variableobjA.displayA();

JAVA PROGRAMMING 22 KKVPRASAD@CSE


//calling class-B method
DemoB objB = new DemoB(200,300);objB.displayB();
//calling class-C method
DemoC objC = new DemoC(250,500,750);objC.displayC();
}}
Output:
Class-A Method : a = 100
Class-B Method : a= 200 b = 300
Class-B Method : a = 250 b = 500 c = 750

3.2.6 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.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...

3.2.7 APPLICATION OF KEYWORD SUPER


First, to distinguish between the variables having the same name in super class andsubclass.
 When the member is called with an object of subclass, the subclass value will be
presented and super class value will get hidden.
 For getting super class value, the keyword super is used.
Second, it is used in defining the constructor of subclass.
 Instead of repeating the assignment of variables of super class, we simply qualifythe
variable with super.

JAVA PROGRAMMING 23 KKVPRASAD@CSE


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 Construtorb=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);

//calling class-B method


objB.displayB();

}
}
Output:
Class-B Method : a = 500 b = 1000

3.2.8 CONSTRUCTOR METHOD AND INHERITANCE

 A constructor in Java is similar to a method with a few differences. Constructor has the same name
as the class name. A constructor doesn't have a return type.
 A Java program will automatically create a constructor if it is not already defined in the program. It
is executed when an instance of the class is created.
 A constructor cannot be static, abstract, final or synchronized. It cannot be overridden.

Java has two types of constructors:


1. Default constructor
2. Parameterized constructor

JAVA PROGRAMMING 24 KKVPRASAD@CSE


What is the order of execution of constructor in Java inheritance?

While implementing inheritance in a Java program, every class has its own constructor. Therefore the
execution of the constructors starts after the object initialization. It follows a certain sequence according
to the class hierarchy. There can be different orders of execution depending on the type of inheritance.

Order of execution of constructor in Single inheritance


In single level inheritance, the constructor of the base class is executed first.

OrderofExecution1.java

class ParentClass
{
ParentClass()
{
System.out.println("ParentClass constructor executed.");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("ChildClass constructor executed.");
}
}
public class OrderofExecution1
{
public static void main(String ar[])
{
System.out.println("Order of constructor execution...");
new ChildClass();
}}
Output:
Order of constructor execution...
ParentClass constructor executed.
ChildClass constructor executed.

3.2.9 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 parameterlist 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.

JAVA PROGRAMMING 25 KKVPRASAD@CSE


Binding
• It involves associating the method call to method body. There are two types of binding asfollows:
Static binding : When the binding is performed at compile time by the compiler, it isknown 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 methodA objA = new A();
objA.display();

//calling the class B methodobjA = new B();


objA.display();
}
}
Output:
Super Class Method
Sub Class Method

3.2.10 DYNAMIC METHOD DISPATCH


 It is a mechanism by which runtime polymorphism is achieved for overriddenmethod in Java.
 It is implemented through super class reference. A super class reference can referto an object of its
subclass.
 A base class pointer can refer to derived class object. There may be many subclasses inherited
from a super class.
 Each subclass has its own version or definition of the overridden method.

JAVA PROGRAMMING 26 KKVPRASAD@CSE


 The dynamic method dispatch chooses the right version of the methodcorresponding to the object
reference.
 In the method, first a reference variable of super class is created.
 The value of subclass object is assigned to the variable and the overriddenmethod is called by the
super class reference.

3.2.11 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[])
{
JAVA PROGRAMMING 27 KKVPRASAD@CSE
//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();
objC.setValues(150,250);
objC.display();
}
}
3.2.12 INTERFACES AND INHERITANCE.
 Multiple inheritance of classes is not permitted in Java.
 To some extent, this restriction can be overcome through interfaces.
 A class may implement more than one interface besides having one super class.
 An interface can extend one or more interfaces, and a class can also implement morethan one
interface.
 An interface is a collection of constants and abstract methods that are implemented by aclass.
 An interface cannot implement itself like a class;
 An interface just contains the method head, and there is no method body. The class that
implements the interface contains the full definition of the method.
import java.io.*;
class Parent1 {
void fun() {
System.out.println("Parent1");
}}
class Parent2 {
void fun() {
System.out.println("Parent2");
}}
class Test extends Parent1, Parent2 {

public static void main(String args[]) {


Test t = new Test();
t.fun();
}}
Output: Compilation error is thrown

Multiple inheritance is not supported by Java using classes, handling the complexity that causes due
to multiple inheritances is very complex. It creates problems during various operations like casting,
constructor chaining, etc, and the above all reason is that there are very few scenarios on which we actually
need multiple inheritances, so better to omit it for keeping things simple and straightforward.

JAVA PROGRAMMING 28 KKVPRASAD@CSE


3.3.1 INTRODUCTION: INTERFACE

 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.
 It cannot be instantiated just like the abstract class.
 Since Java 8, we can have default and static methods in an interface.
 Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

3.3.2 DECLARATION OF INTERFACE

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Internal addition by the compiler
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.

JAVA PROGRAMMING 29 KKVPRASAD@CSE


3.3.3 IMPLEMENTATION OF INTERFACE

In this example, the Printable interface has only one method, and its implementation is provided in
the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone else.
The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDra
wable()
d.draw();
}
}
Output:
drawing circle

3.3.4 MULTIPLE INTERFACES

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.

JAVA PROGRAMMING 30 KKVPRASAD@CSE


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

3.3.5 NESTED INTERFACES

An interface, i.e., declared within another interface or class, is known as a nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested
interface must be referred to by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java programmer.
 The nested interface must be public if it is declared inside the interface, but it can have any access
modifier if declared within the class.
 Nested interfaces are declared static

Syntax of nested interface which is declared within the interface


interface interface_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
TestNestedInterface1.java
interface Showable{
void show();
interface Message{
void msg();
}
JAVA PROGRAMMING 31 KKVPRASAD@CSE
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){
System.out.println("Hello nested interface");}
public static void main(String args[]){
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Output:
hello nested interface

3.3.6 INHERITANCE OF INTERFACES

A class implements an interface, but one interface extends another interface.


interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome

3.3.7 DEFAULT METHODS IN INTERFACES

Java provides a facility to create default methods inside the interface. Methods which are defined
inside the interface and tagged with default are known as default methods. These methods are non-abstract
methods.

Java Default Method Example


In the following example, Sayable is a functional interface that contains a default and an abstract
method. The concept of default method is used to define a method with default implementation. You can
override default method also to provide more specific implementation for the method.

interface Sayable{
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{

JAVA PROGRAMMING 32 KKVPRASAD@CSE


public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Output:
Hello, this is default method
Work is worship

3.3.8 STATIC METHODS IN INTERFACE


Static Methods inside Java 8 Interface
You can also define static methods inside the interface. Static methods are used to define utility methods.
The following example explain, how to implement static method in interface?
interface Sayable{
// default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
Sayable.sayLouder("Helloooo..."); // calling static method
}
}
Output:
Hello there
Work is worship
Helloooo...

3.3.9 FUNCTIONAL INTERFACES

 An Interface that contains exactly one abstract method is known as functional interface. It can have
any number of default, static methods but can contain only one abstract method. It can also declare
methods of object class.
 Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is a
new feature in Java, which helps to achieve functional programming approach.

JAVA PROGRAMMING 33 KKVPRASAD@CSE


interface sayable{
void say(String msg); }
public class FunctionalInterfaceExample implements sayable{
public void say(String msg){
System.out.println(msg); }
public static void main(String[] args) {
FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
fie.say("Hello there");
} }
Output:
Hello there

3.3.10 ANNOTATIONS
Annotations are used to provide supplemental information about a program.
 Annotations start with ‘@’.
 Annotations do not change the action of a compiled program.
 Annotations help to associate metadata (information) to the program elements i.e. instance
variables, constructors, methods, classes, etc.
 Annotations are not pure comments as they can change the way a program is treated by the
compiler.
 Annotations basically are used to provide additional information, so could be an alternative to
XML and Java marker interfaces.

There are three types of annotations.


1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
JAVA PROGRAMMING 34 KKVPRASAD@CSE
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
} }

*****

JAVA PROGRAMMING 35 KKVPRASAD@CSE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy