How to extend Interfaces in Java

Java 8Object Oriented ProgrammingProgramming

An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface extends another interface like a class implements an interface in interface inheritance.

A program that demonstrates extending interfaces in Java is given as follows:

Example

 Live Demo

interface A {
   void funcA();
}
interface B extends A {
   void funcB();
}
class C implements B {
   public void funcA() {
      System.out.println("This is funcA");
   }
   public void funcB() {
      System.out.println("This is funcB");
   }
}
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
      obj.funcA();
      obj.funcB();
   }
}

Output

This is funcA
This is funcB

Now let us understand the above program.

The interface A has an abstract method funcA(). The interface B extends the interface A and has an abstract method funcB(). The class C implements the interface B. A code snippet which demonstrates this is as follows:

interface A {
   void funcA();
}
interface B extends A {
   void funcB();
}
class C implements B {
   public void funcA() {
      System.out.println("This is funcA");
   }
   public void funcB() {
      System.out.println("This is funcB");
   }
}

In the method main() in class Demo, an object obj of class C is created. Then the methods funcA() and funcB() are called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      C obj = new C();
      obj.funcA();
      obj.funcB();
   }
}
raja
Published on 15-Feb-2019 10:35:44
Advertisements