Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements an interface that inherits another interface, it must provide an implementation for all methods required by the interface inheritance chain.
Program 1:
interface A {
void method1();
void method2();
}
// B now includes method1 and method2
interface B extends A {
void method3();
}
// the class must implement all method of A and B.
class gfg implements B {
public void method1()
{
System.out.println("Method 1");
}
public void method2()
{
System.out.println("Method 2");
}
public void method3()
{
System.out.println("Method 3");
}
}
Program 2:
interface Student
{
public void data();
}
class avi implements Student
{
public void data ()
{
String name="avinash";
int rollno=68;
System.out.println(name);
System.out.println(rollno);
}
}
public class inter_face
{
public static void main (String args [])
{
avi h= new avi();
h.data();
}
}
Output
avinash 68
In a Simple way, the interface contains multiple abstract methods, so write the implementation in implementation classes. If the implementation is unable to provide an implementation of all abstract methods, then declare the implementation class with an abstract modifier, and complete the remaining method implementation in the next created child classes. It is possible to declare multiple child classes but at final we have completed the implementation of all abstract methods.
In general, the development process is step by step:
Level 1 – interfaces: It contains the service details.
Level 2 – abstract classes: It contains partial implementation.
Level 3 – implementation classes: It contains all implementations.
Level 4 – Final Code / Main Method: It have access of all interfaces data.
Example:
// Java Program for
// implementation Level wise
import java.io.*;
import java.lang.*;
import java.util.*;
// Level 1
interface Bank {
void deposit();
void withdraw();
void loan();
void account();
}
// Level 2
abstract class Dev1 implements Bank {
public void deposit()
{
System.out.println("Your deposit Amount :" + 100);
}
}
abstract class Dev2 extends Dev1 {
public void withdraw()
{
System.out.println("Your withdraw Amount :" + 50);
}
}
// Level 3
class Dev3 extends Dev2 {
public void loan() {}
public void account() {}
}
// Level 4
class GFG {
public static void main(String[] args)
{
Dev3 d = new Dev3();
d.account();
d.loan();
d.deposit();
d.withdraw();
}
}
Output
Your deposit Amount :100 Your withdraw Amount :50
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods.