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

Java Unit 3

The document provides a comprehensive overview of arrays in Java, covering topics such as declaration, initialization, memory storage, and operations on one-dimensional and multi-dimensional arrays. It also discusses inheritance, interfaces, and jagged arrays, along with practical examples and code snippets for better understanding. Key concepts include dynamic memory allocation, accessing elements, and handling exceptions related to array indexing.
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)
3 views35 pages

Java Unit 3

The document provides a comprehensive overview of arrays in Java, covering topics such as declaration, initialization, memory storage, and operations on one-dimensional and multi-dimensional arrays. It also discusses inheritance, interfaces, and jagged arrays, along with practical examples and code snippets for better understanding. Key concepts include dynamic memory allocation, accessing elements, and handling exceptions related to array indexing.
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

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

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.

Arrays one Dimensional and multidimensional


Array: An array is a data structure that stores elements of same data type in contiguous memory
location. Once array size is defined it cannot be increased (or) decreased. The first element of an
array starts with the index 0.

why arrays?
when you want store student marks, we will declare a variable and store value
int studentMarks;
studentMarks = 92;
what if we need to store 90 students’ marks, are we going to create 90 variables, it will be
very difficult to program and maintain then. arrays will help us to store all these 90 student
marks under same array name differed by array index (address location).

int studentMarks[ ] = new int[90];

studentMarks[0] = 80 // first element in array – marks of 1st student,


studentMarks[1] = 65 // second element in array – marks of 2nd student,
……………

studentMarks[89] = 90 // last element in array – marks of 90th student

Umashankar.5544@[Link]
Declaring an Array –
datatype[ ] arrayname = new datatype[size];
(or)
datatype arrayname[ ] = new datatype[size];
Initializing array -
arrayname[index] = value;
Example –
//To create an array with name myarray of size 3.
int myarray[ ] = new int[3];
Initializing
myarray[0] = 1;
myarray[1] = 2;
myarray[2] = 3;

Note: If the array elements are known at the time of array declaration, we can initialize array
elements along with the declaration itself as
int myarray[ ] = {1,2,3,4,5};
an array, myarray will be created of size 5 with elements stored from index 0 to 4.
[Link](myarray[0]) // prints 1
[Link](myarray[4]) // prints 5

Storage of Arrays in Computer Memory


In Java, arrays are stored in contiguous memory locations.
Memory Structure of Arrays
When an array is created, memory is allocated in two parts:
• Reference to the Array Object: In Java, arrays are objects, so the array variable holds a
reference to the actual memory location where the array elements are stored.
• Elements in Memory: The actual array elements are stored in consecutive memory
locations in the heap. The size of the memory allocated depends on the type and size of the
array.
int[] arr = new int[4]; // Creates an array of 4 integers
• Here arr holds reference to the memory location of the array object, for arr memory is
allocated in stack
• The elements of the array are stored in contiguous memory blocks in the heap, and each
block holds the value of one element.
Heap and Stack in Array Storage
• Heap Memory: Arrays are objects in Java, so they are stored in the heap memory. The
heap is used for dynamic memory allocation. When the array is created, it resides in the
heap, and the array's data (the elements) are stored in contiguous memory blocks.
• Stack Memory: The array reference variable (e.g., arr in int[] arr) is stored in the stack
memory. This reference points to the actual memory location of the array in the heap.

Umashankar.5544@[Link]
Contiguous Memory Allocation
Let's take the example of int[] arr = {10, 20, 30, 40}
Element Value Memory Address
arr[0] 10 1020
arr[1] 20 1024
arr[2] 30 1028
arr[3] 40 1032

If arr[0] is at memory address 1020, and each integer occupies 4 bytes, arr[1] will be at 1024,
arr[2] at 1028, and so on.

Formula for Accessing an Element: To access an element at index i, the memory address can be
calculated as:
Address of arr[i] = Base Address + (i * Size of Element)
Where:
• Base Address is the starting address of the array.
• i is the index of the element.
• Size of Element is the number of bytes required to store each element (e.g., 4 bytes for int,
8 bytes for double).
For example, if arr[0] starts at 1000 and each int takes 4 bytes, to access arr[2]:
Address of arr[2] = 1000 + (2 * 4) = 1008
So, arr[2] (which is 30) will be stored at address 1008.

Write a program to declare an array with size n, then read n no of elements and store them
in that array.

import [Link];
class MyExample {
public static void main(String args[])
{
int n;
Scanner sc = new Scanner([Link]);
[Link](“How many elements you want to store :”)
n = [Link]();
int ary[ ] = new int[n];
// reads n elements from console, and stores in to array, ary
[Link](“Enter ”+n+” no of elements”);
for(int i= 0; i<n;i++ )
{
ary[i] = [Link]();
}
// print each value stored in the array ary,
[Link](“elements stored in array are”);

Umashankar.5544@[Link]
for(int i = 0; i< n; i++)
{
[Link](ary[i]);
}
}
}

OutPut:
How many elements you want to store : 4
Enter 4 no of elements: 2 4 6 8
elements stored in array: 2 4 6 8

Multidimensional arrays:
A multi-dimensional array, is array for arrays. It has multiple levels. The simplest multi-
dimensional array is the 2D array i.e., two-dimensional array

why multi-dimensional array?


when I want to store students’ total marks, a one Dimensional array is enough. what if we
want to store the 6 subject’s marks of 90 students, we cannot accommodate them in one
dimensional array, and we cannot declare 90*6 = 540 variables and memorize them.

In such a scenario, we can use 2-Dimensional array. one dimension to represent student
number and other dimension to represent subject wise marks.

int studentSubjectWiseMarks[ ][ ] = new int[90][6];


A two-dimensional array can also be treated as rows and columns, in the above declaration
studentSubjectWiseMarks we will have 90 rows and 6 columns for each row. where the row
index and column index both starts from 0.

practice indexing,
let’s assign first student, six subject marks with 80, 60,56,70,86,90
studentSubjectWiseMarks[0][0] = 80;
studentSubjectWiseMarks[0][1] = 60;
studentSubjectWiseMarks[0][2] = 56;
studentSubjectWiseMarks[0][3] = 70;
studentSubjectWiseMarks[0][4] = 86;
studentSubjectWiseMarks[0][5] = 90;

second student, six subject marks with 70, 64,58,74,86,70


studentSubjectWiseMarks[1][0] = 70;
studentSubjectWiseMarks[1][1] = 64;
studentSubjectWiseMarks[1][2] = 58;
studentSubjectWiseMarks[1][3] = 74;
studentSubjectWiseMarks[1][4] = 86;
studentSubjectWiseMarks[1][5] = 70;
……………………………………………………………………

Umashankar.5544@[Link]
90th student, six subject marks with 90, 90,90,80,86,70
studentSubjectWiseMarks[89][0] = 90;
studentSubjectWiseMarks[89][1] = 90;
studentSubjectWiseMarks[89][2] = 90;
studentSubjectWiseMarks[89][3] = 80;
studentSubjectWiseMarks[89][4] = 86;
studentSubjectWiseMarks[89][5] = 70;

Note:
The important thing that we should be careful is with indexing of an element. The frequent
error you will observe while dealing with arrays is Array Index Out of Bounds Exception.

int a[ ] = new int[5];


here lower bound index is 0, upper bound index is 4, total 5 elements.
if we try to access an element out of these bounds, we will get, Array Index Out of Bounds
Exception.

a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5; These are perfectly valid.

a[-1] = 3; a[5] = 4; a[56] = 7; these will cause an Array Index Out of Bounds Exception.

Declaring 2 – Dimensional array:

int matrix[ ][ ] = new int[4][3];

Initializing 2-D array:


matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;

matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;

matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;

matrix[3][0] = 10; matrix[3][1] = 11; matrix[3][2] = 12;

rows ↓ Columns 0 1 2

0 matrix[0][0] matrix[0][1] matrix[0][2]
1 matrix[1][0] matrix[1][1] matrix[1][2]
2 matrix[2][0] matrix[2][1] matrix[2][2]
3 matrix[2][0] matrix[3][1] matrix[3][2]

Umashankar.5544@[Link]
write a program to store elements from 1 to 12, using 2-D array of order 4*3
public class MatrixExample
{
public static void main(String args[])
{
int matrix[ ][ ] = new int[4][3]; int
k=1;
for(int i = 0; i<4; i++) // represents rows
{
for(int j = 0; j<3; j++) // represents columns
{
matrix[i][j] = k; // storing elements in array k++;
}
}
// display all the elements in matrix array for(int i = 0; i<4; i++)
{
for(int j = 0; j<3; j++)
{
[Link](matrix[i][j]+” ”);
}
}
}
}

OutPut :1 2 3 4 5 6 7 8 9 10 11 12

write a program that will ask the user for no of rows and no of columns, to declare 2-D
array, and then ask user to enter elements for that matrix. finally print the elements in
matrix format.

import [Link].*;
public class Example
{
public static void main(String args[])
{
int rows, columns;
Scanner sc = new Scanner([Link]);

[Link]("Enter no of rows: ");


rows = [Link](); // reads no of rows

[Link]("Enter no of columns: ");


columns = [Link](); // reads no of columns

// Now declare 2-D array with specified rows and columns int
matrix[][] = new int[rows][columns];
[Link]("Enter elements into matrix: ");
for(int i = 0; i<rows; i++) // represents rows
{
for(int j = 0; j<columns; j++) // represents columns
{
matrix[i][j] = [Link](); // read element into the array
}
}

Umashankar.5544@[Link]
// display all the elements in matrix array
for(int i = 0; i<rows; i++)
{
for(int j = 0; j<columns; j++)
{
[Link](matrix[i][j]+" ");
}
[Link]();
// line break, after printing each row elements
}
}
}

OutPut:

Enter no of rows: 3
Enter no of columns: 3
Enter elements into matrix: 1 2 3 4 5 6 7 8 9
123
456
789

* Note : Finding length of an array, most important How to get no of elements/size of an array
- [Link] will give us the size

example –
int a[] = new int[4];
[Link]([Link]); the output on console will be 4.

Program to print first and last elements of an array


public class ArrayExample
{
public static void main(String args[])
{
int a[ ] = {1,2,3,4};
display(a);
}
static void display(int b[ ])
{
int firstIndex = 0;
// [Link] will give size 4, but last index is 3, as index starts from 0
int lastIndex = [Link]-1;
[Link]("First element is "+b[firstIndex]);
[Link]("Last Element is "+b[lastIndex]);
}
}
OutPut :
First element is 1 Last
Element is 4

Jagged Arrays: Arrays of Varying length

Jagged array is a multidimensional array where member arrays are of different size. each
row will have different no of elements in column .

Umashankar.5544@[Link]
Let say, we want to store Student numbers of 3 sections, where each section have different number
of students.
section 1 contains 64 students,
section 2 contains 65 students
section 3 contains 66 students

how to declare, first declare array with no of rows i.e., 3 int


students[ ][ ] = new int[3][ ];
now declare size of each row, called member array.

students[0] = new int[64];


students[1] = new int[65];
students[2] = new int[66];

write a program that store elements if following manner there should be 3 rows,
1st row stores elements 1,2
2nd row stores elements 3,4,5
3rd row stores elements 6,7,8,9

public class ArrayExample


{
public static void main(String args[])
{
int rows = 3;
int num = 1;

int a[ ][ ] = new int[rows][ ];


a[0] = new int[2];
a[1] = new int[3];
a[2] = new int[4];

for(int i=0; i<[Link]; i++)


{
for(int j = 0;j<a[i].length; j++)
{
a[i][j] = num;
num++;
}
}

for(int i=0; i<[Link]; i++)


{
for(int j = 0;j<a[i].length; j++)
{
[Link](a[i][j]+" ");
}
[Link]();
}

}
}

Umashankar.5544@[Link]
OutPut:
12
345
6789

3-Dimensional Arrays in Java

A 3-dimensional array in Java is a collection of data organized in a structured way across


three dimensions. It consists of array of 2D arrays,
Declaration and Initialization

To declare a 3D array, use three pairs of square brackets:


int[][][] arr = new int[3][4][2]; // A 3D array with 3 layers, 4 rows, and 2 columns

• The first dimension (3) indicates the number of 2D arrays (layers).


• The second dimension (4) specifies the number of rows in each 2D array.
• The third dimension (2) specifies the number of columns in each row.

You can also initialize a 3D array directly with values:

int[][][] arr = {
{ {1, 2}, {3, 4}, {5, 6}, {7, 8} },
{ {9, 1}, {1, 1}, {3, 4}, {1, 6} },
{ {7, 8}, {9, 2}, {1, 2}, {3, 4} }
};
Accessing Elements
To access or modify an element in a 3D array, you use three indices:
arr[0][1][1] = 5; // Sets the value at the 1st layer, 2nd row, and 2nd column as 5

Operation on array elements


Arrays in Java allows various operations, such as adding, updating elements. Below are some
common operations that can be performed on array elements.
1. Accessing Array Elements
we can access any element in an array using its index.

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


[Link]("First element: " + numbers[0]); // Output: 10
[Link]("Third element: " + numbers[2]); // Output: 30

2. Updating Array Elements


we can update the value of an element by assigning a new value to the specified index.

numbers[1] = 25; // Update the second element


[Link]("Updated second element: " + numbers[1]); // Output: 25

3. Iterating Through an Array


we can loop through an array using a for or for-each loop.
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + ": " + numbers[i]);

Umashankar.5544@[Link]
// Using for-each loop
for (int num : numbers) {
[Link](num);
}

5. Finding Maximum or Minimum Element

We can find the maximum or minimum element by iterating through the array.

int max = numbers[0];


for (int i = 1; i < [Link]; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
[Link]("Maximum value: " + max);

int min = numbers[0];


for (int i = 1; i < [Link]; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
[Link]("Minimum value: " + min);

Assigning one array to another array

When one array is directly assigned to another array, both arrays will reference the same
memory location. This means that changes made to one array will affect the other because they
share the same reference.

int[] array1 = {1, 2, 3, 4, 5};


int[] array2 = array1; // Direct assignment

array2[0] = 10; // Modifying array2

[Link]("Array1: ");
for (int num : array1) {
[Link](num + " "); // Output: 10 2 3 4 5
}
[Link]("\nArray2: ");
for (int num : array2) {
[Link](num + " "); // Output: 10 2 3 4 5
}

Dynamic Change of Array Size –

In Java, arrays have a fixed size, which means once created its size cannot be changed
directly. If we want to increase the size of the array, have to create a new array with a larger size
and copy the elements from the original array to the new one.

Umashankar.5544@[Link]
Arrays class in java

The Arrays class in Java is a in-built class provided in the [Link] package. It consists of
several static methods to perform operations on array array elements, such as sorting, searching,
comparing.

operations that the Arrays class provides:

1. Sorting Arrays
2. Searching Arrays
3. Comparing Arrays
4. Copying Arrays
5. Converting Arrays to Strings
6. Checking if Arrays Are Equal

import [Link];

public class ArraysExample


{
public static void main(String[] args)
{
// 1. Sorting Arrays
int[] numbers = {40, 10, 30, 20, 50};
[Link](numbers); // Sorting the array
[Link]("Sorted array: " + [Link](numbers));

// 2. Searching Arrays (binary search)


int key = 30;
int index = [Link](numbers, key); // Search for the value 30
if (index >= 0)
[Link]("Element " + key + " found at index: " + index);
else
[Link]("Element " + key + " not found.");

// 3. Comparing Arrays
int[] numbersCopy = {10, 20, 30, 40, 50}; // Same as the sorted array
boolean areEqual = [Link](numbers, numbersCopy); // Comparing arrays
[Link]("Are the two arrays equal? " + areEqual);

// 4. Copying Arrays
int[] copiedArray = [Link](numbers, [Link]); // Copy the sorted array
[Link]("Copied array: " + [Link](copiedArray));

// 5. Converting Arrays to Strings


String arrayAsString = [Link](numbers); // Convert array to String
[Link]("Array as String: " + arrayAsString);

// 6. Checking if Arrays Are Equal (using mismatch)


int mismatchIndex = [Link](numbers, numbersCopy);
if (mismatchIndex == -1)
[Link]("Both arrays are identical.");

Umashankar.5544@[Link]
else
[Link]("Arrays mismatch at index: " + mismatchIndex);
} // end main
} // end class

Note: [Link] checks if both the arrays elements are completely equal, whereas
[Link] finds starting index where the mismatch occurs between them, if mismatch then it
returns -1.

With out using Arrays class if we want to perform

Sorting of arrays - any sorting algorithm like Bubble Sort can be used

Searching for an element in array – Linear / Binary search can be used

Arrays as Vectors :

Arrays : should be used when the size is fixed and known

Vectors: Used for dynamic size, as the size can be increased / decreased

• It is a class of the [Link] package.


• Dynamic size: Vectors can grow and shrink automatically as elements are added or
removed.
• Synchronized: Vectors are thread-safe, meaning they handle concurrent access in multi-
threaded applications.
• Provides methods like add(), remove(), and insertElementAt() to manage elements
dynamically.

Note: In Java, arrays and vectors are different types of data structures.

import [Link];

public class VectorIntExample {


public static void main(String[] args) {
// Create a Vector to hold integers
Vector<Integer> vector = new Vector<>();

// Adding elements to the Vector


[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]("Vector after adding elements: " + vector);

// Accessing elements
int firstElement = [Link](0);
[Link]("First element: " + firstElement);

// Removing an element
[Link](2); // Remove the element at index 2 (30)
[Link]("Vector after removing element at index 2: " + vector);

Umashankar.5544@[Link]
// Checking the size of the Vector
int size = [Link]();
[Link]("Size of the Vector: " + size);

// Iterating through the Vector


[Link]("Elements in the Vector:");
for (int i = 0; i < [Link](); i++) {
[Link]("Element at index " + i + ": " + [Link](i));
}
}
}

Output :

Vector after adding elements: [10, 20, 30, 40]


First element: 10
Vector after removing element at index 2: [10, 20, 40]
Size of the Vector: 3
Elements in the Vector:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 40

Inheritance - Introduction, Process of Inheritance


Inheritance:
Inheritance is the process of acquiring properties (data members) and functionalities of
one class to another class. It is an important principle of object-oriented programming.
Inheritance helps to achieve code reusability.
‘extends’ is the keyword in java used to inherit one class functionality to another class.
class B extends A
here all the properties and functions under class A will be inherited to class B.
Along with the inherited, class B can also have its own properties and functions.
here, class A is called parent class and class B is called child class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.
Child Class:
The class that extends the features of parent class is known as child class, sub class or derived
class.
Define a class called calculator, given a two integer values it should perform
i) addition
ii) subtraction
iii) multiplication.

Umashankar.5544@[Link]
import [Link];
class Calculator
{
int a, b;
public void add(int i, int j)
{
int sum = i+j;
[Link]("addition is "+ sum);
}
public void substraction(int i, int j)
{
int difference = i-j;
[Link]("subtraction is "+ difference);
}
public void multiply(int i, int j)
{
int multiple = i*j;
[Link]("multiplication is "+ multiple);
}
public static void main(String args[])
{
Calculator obj = new Calculator();
Scanner sc = new Scanner([Link]);
[Link]("Enter value for a: ");
obj.a =[Link]();
[Link]("Enter value for b: ");
obj.b =[Link]();

// perform caliculator operations in these two


values [Link](obj.a, obj.b);
[Link](obj.a, obj.b);
[Link](obj.a, obj.b);

}
}

Umashankar.5544@[Link]
OutPut:
C:\Users\UMA SHANKAR\Desktop>javac [Link]
C:\Users\UMA SHANKAR\Desktop>java
Calculator Enter value for a: 8
Enter value for b: 6
addition is 14
subtraction is 2
multiplication is 48

Define a class called ScientificCalculator, given a two integer values it should perform
i) addition
ii) subtraction
iii) multiplication.
iv) power of
v) modulus
vi) division
we have already written first three operations in class Calculator, why to write that code again
in class ScientificCaliculator ? can’t we reuse that code ?
‘Yes’ by extending the class Calculator in class ScientificCalculator by which it acquires
instance variables a,b and three functionalities add, subtraction and multiply.
import [Link].*;
class ScientificCalculator extends Calculator
{
public static void main(String args[])
{
ScientificCalculator ob = new ScientificCalculator();
Scanner sc = new Scanner([Link]);
[Link]("Enter value for a: ");
ob.a = [Link]();
[Link]("Enter value for a: ");
ob.b = [Link]();
// perform all operations
[Link](ob.a, ob.b);
[Link](ob.a, ob.b);
[Link](ob.a, ob.b);
[Link](ob.a, ob.b);
[Link](ob.a, ob.b);
[Link](ob.a, ob.b);
}
public void power(int i, int j)
{
double sqr = [Link](i,j);
[Link]("power is "+ sqr);
}

public void modulus(int i, int j)

Umashankar.5544@[Link]
{
int mod = i%j;
[Link]("modulus is "+ mod);
}
Public void division(int i, int j)
{
double div = i/j;
[Link]("division is "+div);
}
}
C:\Users\UMA SHANKAR\Desktop>java ScientificCalculator
Enter value for a: 3
Enter value for a: 2
addition is 5
subtraction is 1
multiplication is 6
power is 9.0
modulus is 1
division is 1.0

Types of Inheritance:
Single Inheritance:
In Single Inheritance, there will be only two classes, and one class extends another class.

Class A
{
public void methodA()
{
[Link]("methodA of class A");
}
}

Class B extends A
{
public void methodB()
{
[Link]("methodB of class B");
}

public static void main(String args[])


{
B obj = new B();
[Link]();//calling super class method
[Link]() //calling local method
}
}
Umashankar.5544@[Link]
OutPut
methodA of class A
methodB of class B

Multilevel inheritance:
In Multilevel Inheritance, a class inherits from another derived class. Hence, the
derived class becomes the base class for the new class. refer the diagram.

Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by more than one sub classes.

* Java doesn’t support following two types of inheritances through classes

Multiple Inheritance:
In Multiple Inheritance, a class will extend more than one class. Java does not
support multiple inheritance through classes.

Hybrid Inheritance:
Hybrid inheritance is a combination of Hierarchical and Multiple inheritance.

Umashankar.5544@[Link]
Java doesn't support multiple inheritance because it can lead to ambiguity and
complexity, like diamond problem.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call which method either of class A or B.

Note: Java will raise a compile-time error if you try to inherit more than one class.

Universal Super Class-Object Class

In Java, the Object class is the root class of the Java class hierarchy. Every class in Java
directly or indirectly inherits from the Object class. This means all Java classes are subclasses
of Object. It provides several important methods that are inherited by every Java class, such as
toString(), equals(), hashCode().

Object class defines eight non-static methods that are inherited by all other
classes. A Java class can override any of these eight methods.

1. clone( )
The clone() method is used to create a copy of the object. It returns a new object that is
an exact duplicate of the original. For a class to use this method, it must implement the
Cloneable interface. otherwise, a CloneNotSupportedException will be thrown.

2. equals(Object obj)

The equals() method compares the current object with another object to determine if
they are considered equal. By default, it checks if both references point to the same object in
memory. This method is often overridden to compare the actual data within the objects, such as
fields or attributes.

3. finalize( )

The finalize() method is called by the garbage collector before an object is destroyed.
This method allows you to perform cleanup operations, like releasing resources or saving states,
before the object is removed from memory.

4. getClass( )
The getClass() method returns the runtime class of the object, which includes
information about the object's class type.

Umashankar.5544@[Link]
5. hashCode()

The hashCode() method returns an integer that serves as a unique identifier for the
object.

6. toString( )

The toString( ) method returns a string representation of the object. This is helpful for
debugging and logging, as it allows you to get a readable format of the object. By default, it
returns the class name followed by the object's hash code, but it is common to override this
method to provide more meaningful information about the object.

7. notify( )

The notify() method is used in multithreaded programming to wake up a single thread


that is waiting state. It helps to manage thread communication.

8. notifyAll( )

The notifyAll() method wakes up all threads that are waiting. This is useful when
multiple threads are waiting for a condition to be met.

Inhibiting Inheritance of Class Using Final


Final keyword:
The final keyword in java is used to restrict the access to parent class variables and
methods, and even to prevent the class from being inherited.
A Final can be applied for variables, methods, and class.

Java final variable

If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Write a program using final variable, after initializing it with a value. try to update the
variable again. mention the compile time error that occurs while modifying final
variable.

class Parent
{
final int i =65;
void display()
{
i = 60;
[Link](i);
[Link]("method display of class Parent");
}

public static void main(String args[])


{
Parent ob = new Parent();
[Link]();

Umashankar.5544@[Link]
}

Error :
java:6: error: cannot assign a value to final variable i, i = 60;

Write a program, with method declared final and try to override that in child class.
mention compile time error while you do that.

Note : we cannot override a final method in child class

class Parent
{
final void display()
{
[Link]("This method cannot be overridden in
child class");
}
}

public class Child extends Parent


{
int i = 80;
void display()
{
[Link]("this will not executed, as we cannot override final
method");
}
public static void main(String args[])
{
Child ch = new Child();
[Link](); // calls child display method
}
}

Error:
[Link]: error: display() in Child cannot override display() in
Parent void display()
^
overridden method is
final 1 error

Write a program to extend a class that is final, mention the error you obtain while
implementing that

Note: We cannot extend a final class.


Umashankar.5544@[Link]
final class Parent
{
final void display()
{
[Link]("This method cannot be overriden in
child class");
}
}
public class Child extends Parent
{
public static void main(String args[])
{
Child ch = new Child();
}

[Link]: error: cannot inherit from final Parent


public class Child extends Parent
^
1 error

Access Control and Inheritance

Access control in Java determines which classes can access specific members (variables
and methods) of a class. It is important in inheritance, as it defines how subclasses interact
with superclass members. There are four main access modifiers in Java

1. Public

• Members declared as public can be accessed from any other class in any package.
• When a subclass inherits from a superclass, it can access all public members of the
superclass.

2. Protected

• Members declared as protected can be accessed within the same package and by
subclasses in other packages.
• Subclasses can access protected members of the superclass, even if they are in a
different package.

3. Default (Package-Private)

• Members without any access modifier (default) can only be accessed within the same
package.
• Subclasses in the same package can access default members, but subclasses in different
packages cannot.

4. Private

• Members declared as private can only be accessed within the class where they are
declared.
• Private members are not accessible in subclasses.

Umashankar.5544@[Link]
Following table describes accessibility of different modifiers in java

super Keyword:

The super keyword in java is a reference that is used to refer parent class members.
when a derived class and base class have members (either instance variables or functions)
with same name. JVM will always pick child class member to execute. In such a scenario
If we want to access parent class member’s we can use super reference in child class to
refer parent class members.

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Write program to explain accessing parent class instance overridden(variable with same
name in parent and child class) variable from child class.
class Parent
{
//parent class instance variable
int var=54;
}

public class Child extends Parent


{
//child class instance variable
int var=74;
}
public static void main(String[] args)
{
Child obj = new Child();
[Link]();
}

Umashankar.5544@[Link]
void display()
{
[Link](var); //refers child class var
[Link]([Link]); // refers parent class var
}
}
74
54
program to explain accessing parent class overridden method from child class.
class Parent
{
//parent class print method
void print()
{
[Link]("print method of parent class");
}
}

public class Child extends Parent


{

public static void main(String[] args)


{
Child obj = new Child();
[Link]();
}
void display()
{
print(); // executes child class print method
[Link](); // executed parent class print method
}
//child class print method
void print()
{
[Link]("print method of child class");
}

OUTPUT:
print method of child class
print method of parent class

Write a program to invoke parent class no argument constructor from child class
using super

class Parent
{
//parent class constructor Parent()
{
[Link]("no argument constructor of parent class");
}

Umashankar.5544@[Link]
}

public class Child extends Parent


{
//child class constructor Child()
{
super(); // calls parent class no argument constructor
[Link]("no argument constructor of child class");
}
public static void main(String[] args)
{
Child obj = new Child(); // calls child class constructor
}
}

OUTPUT:
no argument constructor of parent class no argument
constructor of child class

Write a program to invoke parent class constructor with arguments from child class
using super

class Parent
{
//parent class constructor
int a,b;
Parent()
{
[Link]("parent class constructor without arguments");
}
Parent(int i, int j)
{
a = i;
b = j;
[Link]("parent class instance variables are initialized");
[Link]("a = "+a+" b = "+b);
}
}

public class Child extends Parent


{
//child class constructor Child()
{
super(5,4); //calls parent class constructor with arguments
[Link]("If we use super it should be first statement in constructor");
}
public static void main(String[] args)
{
Child obj = new Child(); // calls child class constructor
}
}

Umashankar.5544@[Link]
OUTPUT:
parent class instance variables are initialized a = 5 b = 4
If we use super it should be first statement in constructor.

Constructor and Inheritance:

• Constructors are not inherited in the same way as methods. A subclass does not inherit
the constructors of its superclass.
• However, a subclass can call a superclass constructor using the super() keyword,
allowing it to initialize the inherited properties.

Using super():

• The super() call must be the first statement in the subclass constructor.
• It allows the subclass to invoke a specific constructor of the superclass, passing any
required parameters.

Note: refer to the above super keyword for detailed explanation

Method Overriding:
If subclass (child class) has the same method as declared in the parent class, then the
function is said to be overridden in child class. When we create on object for child class and
try to invoke the method with same name as in parent class, method from child class will be
invoked. It is also called as dynamic polymorphism.

write a program to explain how method overriding takes place between parent and child
class

class Parent
{
void display()
{
[Link]("method display of class Parent");
}
}

public class Child extends Parent


{
void display()
{
[Link]("method display of class Child");
}
public static void main(String args[])
{
Child ch = new Child();
[Link](); // calls child display method
}
}

OUTPUT:
method display of class Child

Umashankar.5544@[Link]
Note: When we want to access parent class overridden functions we can do, using the super
keyword.

Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at runtime rather than at compile-time. It happens when a superclass reference variable
is used to refer to an object of a subclass, and the overridden method of the actual object
(subclass) is called.

• The actual method that gets called is determined by the type of object, not by the type of
reference.
• At compile-time, the compiler only knows the reference type (superclass), but at
runtime, Java uses the object type (subclass) to determine which method to invoke.

class Parent {

void display() {
[Link]("This is parent class method");
}
}

class Child extends Parent{


// Overriding the display method in the child class (subclass)
void display() {
[Link]("This is a child class method");
}
}

public class Main {


public static void main(String[] args) {
// Superclass reference, subclass object
Parent ref= new Child();

// Dynamic method dispatch: Calls the overridden method in the Child class
[Link](); // Output: "This is child class method"
}
}

Abstract classes

Abstract method: A method which is declared as abstract and does not have
implementation is known as an abstract method.
abstract void printStatus(); // no functionality will be defined when declared abstract.

Abstract class:

A class which is declared abstract, is known as an abstract class. It can have both
abstract and non-abstract methods.
1. An abstract class must be declared with an abstract keyword.
2. It can have abstract and non-abstract methods.

Umashankar.5544@[Link]
3. object cannot be created for abstract classes.
4. It can have constructors and static methods.
5. It can have final methods which will force the subclass not to change the body of the
method.

NOTE : To use the abstract class we must extend the abstract class, and need to
define the functionality for its abstract methods and we can use the inherited non
abstract methods of it.

Write a program explaining how to use abstract and non-abstract methods of an


abstract class.

abstract class Parent


{
void method1()
{
[Link]("this is a non-abstract method class Parent");
}
// abstract methods will not have any functionality
abstract int method2(int a, int b);
}
class Child extends Parent
{
public static void main(String args[])
{
Child ob = new Child();
ob.method1();
int sum = ob.method2(8,9);
[Link]("sum of two values is "+sum);
}
int method2(int i, int j)
{
return i+j;
}
}
OUTPUT:
this is a non-abstract method class Parent sum of two
values is 17

Note : If we extend an abstract class, we must implement all the abstract methods of the parent
abstract class. otherwise we should declare implementing class also as abstract.

Interfaces:
An interface is declared by keyword interface, in interface all the methods will be
abstract.
1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.

Umashankar.5544@[Link]
4. An interface is not extended by a class, it is implemented by a class.
5. An interface can extend multiple interfaces.

Interface declaration
interface interfaceName
{
method declaration // public and abstract though it was not specified
}
Define an interface which specifies there should be functions called sum and multiply
that accepts two integer numbers and returns sum and multiplication values
respectively. also write a class to implement that interface.
interface InterfaceOne
{
int sum(int a, int b);
int multiply(int i, int j);
}

class Impl implements InterfaceOne


{
public int sum(int a1, int a2)
{
int sum;
sum = a1+a2;
return sum;
}
public int multiply(int b1, int b2)
{
int mul;
mul = b1 * b2;
return mul;
}
public static void main(String args[])
{
Impl obj = new Impl();
int r1 = [Link](2,4);
[Link]("sum of values is "+r1);
int r2 = [Link](3, 4);
[Link]("multiplication of values is "+r2);
}
}

OUTPUT:
sum of values is 6 multiplication of values is 12

Umashankar.5544@[Link]
Multiple Interfaces
A class can implement more than one interface at a time, but can extend only one class.
Example :

// First interface for the sum method


interface SumInterface {
int sum(int a, int b);
}

// Second interface for the multiply method


interface MultiplyInterface {
int multiply(int i, int j);
}

// The Impl class implements both interfaces


class Impl implements SumInterface, MultiplyInterface {
// Implementing the sum method
public int sum(int a1, int a2) {
return a1 + a2;
}

// Implementing the multiply method


public int multiply(int b1, int b2) {
return b1 * b2;
}

// Main method to test the implementations


public static void main(String args[]) {
Impl obj = new Impl();
int r1 = [Link](2, 4);
[Link]("Sum of values is " + r1);

int r2 = [Link](3, 4);


[Link]("Multiplication of values is " + r2);
}
}

Nested Interfaces
In Java, nested interfaces are interfaces that are defined within another class or
interface. Just like nested classes, you can declare an interface inside another interface or
class.
Types of Nested Interfaces:
• Interface inside a class: You can define an interface inside a class.
• Interface inside another interface: You can define an interface inside another interface,
which implies a relationship between the two interfaces.

Umashankar.5544@[Link]
1. Interface Inside a Class
When an interface is nested inside a class, it behaves like a regular interface but is
enclosed within the scope of the class. Any class implementing this nested interface must
either be an inner class or an external class that refers to the outer class.
class OuterClass {
// Nested interface inside a class
interface NestedInterface {
void display();
}
}
// Implementing the nested interface in an external class
class ImplementingClass implements [Link] {
public void display() {
[Link]("This is the implementation of the nested interface.");
}
}
public class Main {
public static void main(String[] args) {
[Link] obj = new ImplementingClass();
[Link]();
}
}
2. Interface Inside Another Interface
When an interface is nested inside another interface, any class implementing the outer
interface can also implement the nested interface.
interface OuterInterface {
// Nested interface inside an interface
interface InnerInterface {
void innerMethod();
}
void outerMethod();
}
// Class implementing both outer and inner interfaces
class ImplementingClass implements OuterInterface, [Link] {
public void outerMethod() {
[Link]("Outer interface method.");
}

Umashankar.5544@[Link]
public void innerMethod() {
[Link]("Inner interface method.");
}
}
public class Main {
public static void main(String[] args) {
ImplementingClass obj = new ImplementingClass();
[Link]();
[Link]();
}
}

Inheritance of Interfaces - Extending Interfaces


An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child interface
inherits the methods(abstract) of the parent interface.

// Interface for addition


interface CalculatorV1 {
int add(int a, int b); // Abstract method for addition
}

// Interface for multiplication that extends CalculatorV1


interface CalculatorV2 extends CalculatorV1 {
int multiply(int a, int b); // Abstract method for multiplication
}

// Implementation class
class Impl implements CalculatorV2 {
@Override
public int add(int a, int b) {
return a + b; // Implementation of addition
}

@Override
public int multiply(int a, int b) {
return a * b; // Implementation of multiplication
}

public static void main(String[] args) {


Impl calculator = new Impl();
[Link]("Addition: " + [Link](5, 3));
// Output: Addition: 8
[Link]("Multiplication: " + [Link](5, 3));
// Output: Multiplication: 15
}
}

Umashankar.5544@[Link]
Default and static methods in interface
Default Methods
• Definition: Default methods allow you to add new methods to an interface without
breaking existing implementations. They provide a body (implementation) and can be
overridden by implementing classes. A default method is defined using the default
keyword.
• Usage: They are useful for providing common functionality that can be shared among
multiple implementing classes.

interface Int1 {
void m1(); // Abstract method

// Default method
default void m2() {
[Link]("new method m2 provided with default functionality. No need to
override");
}
}

class Impl implements Int1 {


@Override
public void m1() {
[Link]("old method m1 is overridden in class impl");
}
}

public class Main {


public static void main(String[] args) {
impl obj = new Impl();
obj.m1 (); // Output: old method m1 is overridden in class impl.
obj.m2 (); // Output: new method m2 provided with default functionality. No need to
override.
}
}

Static Methods
• Definition: Static methods belong to the interface itself, not to any specific instance.
They can be called without creating an instance of the interface. A static method is
defined using the static keyword.
• Usage: They are often used for utility or helper methods related to the interface.

Umashankar.5544@[Link]
interface MathOperations {
static int add(int a, int b) {
return a + b; // Static method implementation
}
}
public class Main {
public static void main(String[] args) {
int result = [Link](5, 3); // Call static method without creating an instance
[Link]("Sum: " + result); // Output: Sum: 8
}
}

Functional Interfaces
Functional interface is an interface that contains exactly one abstract method. These
interfaces are primarily used in functional programming, a key feature of Java 8 and beyond.
They enable the use of lambda expressions to make code shorten and readable.
Functional Interfaces can contain
1. Exactly One Abstract Method: A functional interface must have only one abstract
method. This is the method that lambda expressions can implement.
2. Default and Static Methods: A functional interface can still have any number of default
and static methods, as long as it has one abstract method.
3. @FunctionalInterface Annotation: Java provides this optional annotation to clearly
indicate that an interface is intended to be functional. If you try to add more than one
abstract method, the compiler will give an error when this annotation is used.
Lambda Expression
Lambda expressions in Java provide a way to implement the functional interfaces more
concisely. They allow you to write anonymous methods in a simple and readable way. Lambda
expressions were introduced in Java 8 to enable functional programming.
Syntax – (parameter list) -> { body }
interface Calculator {
int calculate(int a, int b); // Single abstract method
}
public class Main {
public static void main(String[] args) {
// Lambda expression for the 'calculate' method of Calculator interface
Calculator addition = (a, b) -> a + b;
Calculator multiplication = (a, b) -> a * b;
[Link]("Addition: " + [Link](5, 3)); // Output: 8
[Link]("Multiplication: " + [Link](5, 3)); // Output: 15
}
}

Umashankar.5544@[Link]
Annotations
Annotations in Java are special markers or labels that provide additional information
about the code but do not change how the code works. They are like instructions or notes for
the compiler or other tools to understand how to handle certain parts of the program.
Annotations can be applied to classes, methods, fields, and more, to give extra details or to
control specific behaviors (like warnings, deprecation, or overriding methods).

Common Java Annotations:


1. @Override
• Indicates that a method is overriding a method in its superclass.
• Helps prevent errors by ensuring that a method is actually overriding a superclass
method.
class Parent {
void display() {
[Link]("Parent");
}
}
class Child extends Parent {
@Override
void display() {
[Link]("Child");
}
}
2. @Deprecated
• Marks a method, class, or field as deprecated, meaning it is outdated and should not be
used in new code. The compiler will warn you if you use a deprecated element.
@Deprecated
void oldMethod() {
[Link]("This method is deprecated.");
}
3. @SuppressWarnings
• Instructs the compiler to ignore specific warnings, such as deprecated, unchecked
warnings.

import [Link];
public class DeprecatedExample {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Date date = new Date();
// Deprecated method usage
int year = [Link](); // This will show a deprecated warning
[Link]("Year: " + year);
}
}

Umashankar.5544@[Link]
4. @FunctionalInterface
• Marks an interface as a functional interface, which means it should have exactly one
abstract method. Used for lambda expressions in Java.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b); // Single abstract method
}

Umashankar.5544@[Link]

You might also like