Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views43 pages

Java3 (New)

Uploaded by

shiva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views43 pages

Java3 (New)

Uploaded by

shiva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

UNIT – III

Arrays :

Java Arrays:

An array is a collection of similar types of data.

How to declare an array in Java :


dataType[] arrayName;

Initialize Arrays in Java:


//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};

Example: Access Array Elements :


class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Operations on Array Elements :
Operations on array elements in Java involve various manipulations and interactions with the data stored
within an array. Common operations include:

 Accessing Elements: Individual elements are accessed using their index, which starts from 0.
EX:
int[] numbers = {10, 20, 30};
int firstElement = numbers[0]; // Accesses the element at index 0 (value 10)

 Modifying Elements: Values of elements can be changed by assigning a new value to a specific
index.

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


numbers[1] = 25; // Changes the element at index 1 to 25

 Traversing Elements: Iterating through all elements, typically using a for loop or an enhanced for-
each loop.

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


for (int num : numbers) {
System.out.println(num); // Prints each element
}
Searching Elements: Finding a specific element or its index. The java.util.Arrays class provides methods
like binarySearch for sorted arrays.
import java.util.Arrays;
int[] numbers = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(numbers, 30); // Returns the index of 30 (which is 2)

 Sorting Elements: Arranging elements in a specific order (ascending or descending). The


java.util.Arrays class offers the sort method.

import java.util.Arrays;
int[] numbers = {50, 20, 40, 10, 30};
Arrays.sort(numbers); // Sorts the array: {10, 20, 30, 40, 50}

 Filling Elements: Assigning a specific value to all elements in an array using Arrays.fill().

import java.util.Arrays;
int[] numbers = new int[5];
Arrays.fill(numbers, 7); // Fills the array with 7s: {7, 7, 7, 7, 7}

 Comparing Arrays: Checking if two arrays are equal using Arrays.equals().


import java.util.Arrays;
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean areEqual = Arrays.equals(arr1, arr2); // Returns true

EX:

import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int size=10, i, search, first, last, middle;
int[] arr = new int[size];
Scanner scan = new Scanner(System.in);
System.out.print("Enter 10 Elements (in Ascending): ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Enter an Element to Search: ");
search = scan.nextInt();
first = 0;
last = size-1;
middle = (first+last)/2;

while(first<=last)
{
if(arr[middle]<search)
{
first = middle+1;
}
else if(arr[middle]==search)
{
System.out.println("\nThe element is available at Index No." +middle);
break;
}
else
{
last = middle-1;
}
middle = (first+last)/2;
}
if(first>last)
{
System.out.println("\nThe element is not available in given array");
}
}
}
Assigning Array to Another Array :
Copying an array can be done in several ways, depending on our needs such as shallow copy or deep copy.
Assigning one array to another array variable results in a shallow copy.
shallow copy meaning both array variables will refer to the same underlying array object in memory.
Shallow Copy (Assignment Operator):
int[] originalArray = {1, 2, 3};
int[] assignedArray = originalArray; // assignedArray now points to the same object as originalArray

// Changes to assignedArray will affect originalArray


assignedArray[0] = 99;
System.out.println(originalArray[0]); // Output: 99
Deep Copy (Creating a new independent array):
If an independent copy is required, a deep copy is necessary, ensuring changes to one array do not affect the
other. Several methods achieve this: Looping and Copying Elements.

int[] originalArray = {1, 2, 3};


int[] copiedArray = new int[originalArray.length];
for (int i = 0; i < originalArray.length; i++) {
copiedArray[i] = originalArray[i];
}

EX:
public class Test {
public static void main(String[] args) {
int a[] = { 1, 8, 3 };

// Create an array b[] of same size as a[]


int b[] = new int[a.length];

// Incorrectly attempt to copy by assigning a to b


// it makes b refer to the same array as a
b = a;

// Change to b[] will also reflect in a[]


// as a and b refer to same array in memory
b[0]++;

System.out.println("Contents of a[] ");


for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println("\n\nContents of b[] ");
for (int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
}
}
Dynamic Change of Array Size :
Dynamic Array can be added as the array increases its size as it is full. The size of the new array increases
to double the size of the original array. Dynamic arrays have a dynamic size modifiable at runtime. Now
all elements are retained in a new array which is in the specified array domain size and the rest are added
after them in the newly formed array.

EX:
// Java Program to Implement a Dynamic Array

// User Defined Array


class Array {

private int arr[];


private int count;

// Method to return length of array


public Array(int size){
arr = new int[size];
}

// Method to print array


public void printArray(){

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


System.out.print(arr[i] + " ");
}

// Method to insert element in array


public void insert(int ele){

if (arr.length == count) {

// Creating a new array double the size


// of array declared above
int newArr[] = new int[2 * count];

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


newArr[i] = arr[i];

// Assigning new array to original array


arr = newArr;
}

arr[count++] = ele;
}
}

public class Main {


public static void main(String[] args){

// Creating object of Array(user-defined) class


Array numbers = new Array(3);
// Adding elements to array
numbers.insert(10);
numbers.insert(20);
numbers.insert(30);

// Extra element exceeding array size


numbers.insert(50);

// Calling printArray() method


numbers.printArray();
}
}

Sorting of Arrays :
The sort() method sorts an array in ascending order. This method sorts arrays of strings alphabetically, and
arrays of integers numerically.

EX:
// Java Program to Implement sort()
import java.util.Arrays;

class Geeks {
public static void main(String args[]) {

// Integer Array
int[] a = { 2, -1, 3, 4 };

// Character Array
char[] b = { 'b', 'a', 'c', 'b' };
// Sort both arrays
Arrays.sort(a);
Arrays.sort(b);

// Print sorted integer array


System.out.print("");
for (int n : a) {
System.out.print(n + " ");
}

// Print sorted character array


System.out.print("\n");
for (char c : b) {
System.out.print(c + " ");
}
}
}
Search for Values in Arrays :
Searching for values within arrays in Java can be accomplished using several methods, depending on
whether the array is sorted and the specific requirements of the search.

EX:
public class ArraySearch {
public static boolean linearSearch(int[] arr, int target) {
for (int element : arr) {
if (element == target) {
return true; // Value found
}
}
return false; // Value not found
}
}
EX:
// Java program to check whether
// an element is present in array or not
import java.util.Arrays;
import java.util.stream.IntStream;

class Geeks
{
// Method to check if the specified element
// is present in the array or not
private static boolean isElementPresent(int[] arr, int key)
{
// check if the specified element
// is present in the array or not
// using Linear Search method
for (int element : arr) {
if (element == key) {
return true;
}
}

return false;
}

public static void main(String[] args)


{
// Get the array
int arr[] = { 3, 5, 7, 2, 6, 10 };

// Get the value to be checked


int key = 7;

// Check if this value is


// present in the array or not
boolean res = isElementPresent(arr, key);

System.out.println("Is " + key


+ " present in the array: "
+ res);

}
}

EX:
// Java program to check whether
// an element is present in array or not
import java.util.Arrays;
import java.util.stream.IntStream;

class Geeks
{
// Method to check if the specified element
// is present in the array or not
private static boolean isElementPresent(int[] arr, int key)
{
// sort given array
Arrays.sort(arr);

// check if the specified element


// is present in the array or not
// using Binary Search method
int res = Arrays.binarySearch(arr, key);

// if the element is not present in the array


// then the result will be negative
// so we will return false
if (res < 0)
return false;

// otherwise element is present in the array


return true;
}

public static void main(String[] args)


{

// Get the array


int arr[] = { 3, 5, 7, 2, 6, 10 };

// Get the value to be checked


int key = 17;

// Check if this value is


// present in the array or not
boolean res = isElementPresent(arr, key);

System.out.println("Is " + key


+ " present in the array: "
+ res);

}
}

The Arrays class in Java, found in the java.util package, is a utility class that provides static methods for
manipulating arrays. It is part of the Java Collections Framework and offers various functionalities for
common array operations.
Key aspects of the Arrays class:
Static Methods:
All methods within the Arrays class are static, meaning they can be called directly using the class name
(e.g., Arrays.sort()) without needing to create an instance of the Arrays class.
Array Manipulation:
It provides methods for a wide range of array manipulations, including:
Sorting: sort() methods for various primitive types and objects.
Searching: binarySearch() for efficiently searching sorted arrays.
Comparing: equals() for comparing two arrays for equality.
Filling: fill() for assigning a specific value to all elements of an array.
Copying: copyOf() and copyOfRange() for creating copies of arrays or sub-arrays.
Converting to List: asList() to view an array as a fixed-size List.
NullPointerException:
Most methods in the Arrays class throw a NullPointerException if the specified array reference is null,
unless otherwise noted in the method's documentation.
Implementation Notes:
The documentation for the methods often includes brief descriptions of their implementations, which are
considered implementation notes rather than parts of the strict specification. This allows implementers to
substitute different algorithms as long as the method's specified behavior is maintained.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array
o Three-dimensional Arrays

Single Dimensional Array in Java


class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

EX:
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Three-dimensional Arrays :

a three-dimensional (3D) array is essentially an array of two-dimensional (2D) arrays. This structure allows
for storing data in a cube-like or layered fashion, where each element is accessed using three indices.

Declaration and Initialization:


 Declaration: A 3D array is declared by specifying the data type followed by three sets of square brackets []
[][].
 Initialization with fixed dimensions: You can initialize a 3D array by specifying the size of each
dimension during creation.
int[][][] threeDArray = new int[2][3][4]; // 2 "tables", 3 rows, 4 columns

This creates an array capable of holding 2 * 3 * 4 = 24 integer elements.


 Initialization with values: You can also initialize a 3D array directly with values using nested curly braces.
int[][][] threeDArray = {

{ {1, 2, 3}, {4, 5, 6} },

{ {7, 8, 9}, {10, 11, 12} }

};

EX:

// Java Program to Demonstrate

// Three Dimensional Array

import java.io.*;

class Geeks

public static void main(String[] args){

// Array Created and Initialized

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

// Defining the x,y,z in Multi

// Dimensional Array

int n = arr.length;

int m = arr[0].length;

int o = arr[0][0].length;
// Printing the Array

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

for (int j = 0; j < m; j++) {

for (int k = 0; k < o; k++) {

System.out.println("arr[" + i + "][" + j + "][" + k + "] = " + arr[i][j][k]);

Arrays of Varying Lengths :

arrays have a fixed length determined at the time of creation, arrays of varying lengths can be achieved
through specific structures:

1. Jagged Arrays (Ragged Arrays):


 A jagged array is a multidimensional array where each "row" (inner array) can have a different length.
 It is essentially an array of arrays, where each element of the main array is itself an array, and these inner
arrays can vary in size.
EX:

int[][] jaggedArray = new int[3][]; // Declare a jagged array with 3 rows

jaggedArray[0] = new int[]{1, 2}; // First row has length 2

jaggedArray[1] = new int[]{3, 4, 5}; // Second row has length 3

jaggedArray[2] = new int[]{6, 7, 8, 9}; // Third row has length 4

2. Dynamic Arrays (ArrayList):


 ArrayList is a class in the java.util package that provides a resizable array implementation.
 Unlike fixed-size arrays, ArrayList can dynamically grow or shrink as elements are added or removed.

EX :

import java.util.ArrayList;
ArrayList<String> dynamicArray = new ArrayList<>(); // Create an ArrayList of Strings

dynamicArray.add("Apple"); // Add elements

dynamicArray.add("Banana");

dynamicArray.add("Cherry");

// The size of dynamicArray can change as more elements are added or removed.Arrays as Vectors :

the Vector class provides functionality similar to a dynamic array, allowing for a growable array of
objects. While both Vector and traditional Java arrays can store collections of elements, they differ in key
aspects:
Key Differences:
Fixed vs. Dynamic Size:
Java arrays have a fixed size defined at creation and cannot be resized. Vector, on the other hand, is
dynamic and can automatically expand or shrink as elements are added or removed.
Synchronization:
Vector is a legacy class and is synchronized, meaning its methods are thread-safe. This can lead to
performance overhead in single-threaded environments compared to ArrayList, which is not synchronized
by default.
Legacy Class:
Vector was part of the original Java Collections Framework, but ArrayList is generally preferred for new
code due to its better performance in most scenarios.
Converting between Arrays and Vectors:
Array to Vector:
Using Collections.addAll(): This method can efficiently add all elements from an array to a Vector.
Using Arrays.asList(): This creates a fixed-size List from an array, which can then be used to initialize
a Vector.
Using a loop: Iterate through the array and add each element to the Vector one by one.
Vector to Array:
Using Vector.toArray(): This method returns a new array containing all elements from the Vector. An
overloaded version allows specifying the runtime type of the returned array.
Example of converting an array to a Vector:
import java.util.Arrays;

import java.util.Vector;

public class ArrayToVector {

public static void main(String[] args) {

String[] myArray = {"apple", "banana", "cherry"};

Vector<String> myVector = new Vector<>(Arrays.asList(myArray));


System.out.println("Vector elements: " + myVector);

Example of converting a Vector to an array:

import java.util.Vector;

public class VectorToArray {

public static void main(String[] args) {

Vector<String> myVector = new Vector<>();

myVector.add("red");

myVector.add("green");

myVector.add("blue");

String[] myArray = new String[myVector.size()];

myArray = myVector.toArray(myArray);

System.out.println("Array elements:");

for (String s : myArray) {

System.out.println(s);

}
UNIT – II

Inheritance in Java is a mechanism one object acquires all the properties and behaviors of a parent object.
It is an important part of OOPs (Object Oriented programming system).

inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of
Employee.

EX:

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.

EX:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.

EX:

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();
}}

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

Ex:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Method Overriding in Java


subclass (child class) has the same method as declared in the parent class, it is known as method overriding in
Java.
a subclass provides the specific implementation of the method that has been declared by one of its parent class, it
is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

EX :
class Animal {
// method in the superclass
public void eat() {
System.out.println("I can eat");
}
}

// Dog inherits Animal


class Dog extends Animal {

// overriding the eat() method


@Override
public void eat() {
System.out.println("I eat dog food");
}

// new method in subclass


public void bark() {
System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// call the eat() method


labrador.eat();
labrador.bark();
}
}
Dynamic method dispatch or Runtime polymorphism in Java
Runtime Polymorphism in Java is achieved by Method overriding in which a child class overrides a method in
its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child
class uses the super keyword within the overriding method. This method call resolution happens at runtime and
is termed as Dynamic method dispatch mechanism.
EX :
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Example of Abstract class that has an abstract method

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle
classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the factory method
later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}

Final Keyword In Java

he java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first
learn the basics of final keyword.

1) Java final variable

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

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.

EX:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

2) Java final method

If you make any method as final, you cannot override it.


Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


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

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Java final class

If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda1 extends Bike{


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

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
interface in Java :

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.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.

Java Interface also represents the IS-A relationship.

declare an 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.
}

Interface fields are public, static and final by default, and the methods are public and abstract.
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.

Example:

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();
}
}

EX:2
// Java program to demonstrate the
// real-world example of Interfaces

import java.io.*;
interface Vehicle {

// all are the abstract methods.


void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements Vehicle{

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements Vehicle {

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}

}
class GFG {

public static void main (String[] args) {

// creating an inatance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);

System.out.println("Bicycle present state :");


bicycle.printStates();

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}
Inheritance of Interfaces :(Extending Interfaces in Java)
one interface inherits from another interface, that sub-interface inherits all the methods and constants that its
super interface declared. In addition, it can also declare new abstract methods and constants. To extend an
interface, you use the extends keyword just as you do in the class definition. Unlike a subclass which can
directly extend only one subclass, an interface can directly extend multiple interfaces.

interface Interface1

public void f1();

//Interface2 extending Interface1

interface Interface2 extends Interface1

public void f2();

class x implements Interface2

//definition of method declared in interfacel

public void f1()

System.out.println("Contents of Method f1() in Interface1");

public void f2()

System.out.println("Contents of Method f2() in Interface2");

public void f3()

System.out.println("Contents of Method f3() of Class X");


}

class ExtendingInterface

public static void main(String[] args)

Interface2 v2; //Reference variable of Interface2

v2 = new x(); //assign object of class x

v2.f1();

v2.f2();

x xl=new x();

xl.f3();

Java Nested Interface

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.

Syntax of nested interface :

interface interface_name{
...
interface nested_interface_name{
...
}
}

Example :

interface Showable{
void show();
interface Message{
void msg();
}
}
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();
}
}

Default Methods in Interfaces :


Default methods, introduced in Java 8, are a feature that allows interfaces to define methods with a concrete
implementation. This was a significant change to the Java language, as interfaces prior to Java 8 could only
contain abstract methods (method declarations without a body).

interfaces could only have abstract methods. The implementation of these methods has to be provided in a
separate class. So, if a new method is to be added in an interface, then its implementation code has to be
provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the
concept of default methods which allow the interfaces to have methods with implementation without affecting
the classes that implement the interface.
EX :
// A simple program to Test Interface default
// methods in java
interface TestInterface
{
// abstract method
public void square(int a);

// default method
default void show()
{
System.out.println("Default Method Executed");
}
}

class TestClass implements TestInterface


{
// implementation of square abstract method
public void square(int a)
{
System.out.println(a*a);
}

public static void main(String args[])


{
TestClass d = new TestClass();
d.square(4);

// default method executed


d.show();
}
}

Static Methods in Interface :


tatic Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike
other methods in Interface, these static methods contain the complete definition of the function and since the
definition is complete and the method is static, therefore these methods cannot be overridden or changed in the
implementation class.
the static method in an interface can be defined in the interface, but cannot be overridden in Implementation
Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.
EX :
interface Calculator {
// Abstract method
int add(int a, int b);

// Static method
static int multiply(int a, int b) {
return a * b;
}
}

class MyCalculator implements Calculator {


@Override
public int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


MyCalculator calc = new MyCalculator();
System.out.println("Sum: " + calc.add(5, 3)); // Calling instance method

System.out.println("Product: " + Calculator.multiply(5, 3)); // Calling static method directly on interface


}
}

Functional Interfaces :
A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can
have multiple default or static methods, but only one abstract method.
EX:
@FunctionalInterface

interface Square {
int calculate(int x);
}

class Geeks {
public static void main(String args[]) {
int a = 5;

// lambda expression to define the calculate method


Square s = (int x) -> x * x;

// parameter passed and return type must be same as defined in the prototype
int ans = s.calculate(a);
System.out.println(ans);
}
}
Annotations :
Annotations are used to represent the syntactic metadata related to the class, interface, methods or fields used in
the source code and some additional information which is used by java interpreter and the JVM.
An "annotation interface" refers to a special type of interface declared using the @interface keyword, which is
used to define custom 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.
See below code for example.
 Annotations basically are used to provide additional information, so could be an alternative to XML
and Java marker interfaces.
Ex :

// Java Program to Demonstrate Type Annotation

// Importing required classes


import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

// Using target annotation to annotate a type


@Target(ElementType.TYPE_USE)

// Declaring a simple type annotation


@interface TypeAnnoDemo{}

// Main class
class GFG {

// Main driver method


public static void main(String[] args) {

// Annotating the type of a string


@TypeAnnoDemo String string = "I am annotated with a type annotation";
System.out.println(string);
abc();
}

// Annotating return type of a function


static @TypeAnnoDemo int abc() {

System.out.println("This function's return type is annotated");

return 0;
}
}

You might also like