Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
interface
abstract
class

What is a Java interface?

Educative Answers Team

Java interface is an abstract class which provides data abstraction. Abstraction is a way to provide users with only relevant and essential information and hide the rest.

Java interface is an abstract class which is used to group related methods, classes or data with empty bodies.

Differences between an interface and a class:

  • An interface cannot be instantiated ie., you cannot create an object of an interface. However, classes may have an object.

  • An interface is implemented without any constructors.

  • Each field in an interface must be declared final and static.

  • An interface is implemented by another class. It is never extended by a class.

  • An interface, however, may extend multiple interfaces.

svg viewer

Why do we need interfaces?

  • Data abstraction
  • To achieve multiple inheritances
  • Allow different objects to interact easily
  • Facilitate reuse of the software

Example 1

This example shows how an interface is implemented by a class. (Pig implements Animal)

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig is calling you: WEE WEEE WEEEEE");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Sleep Sound: ZzzzzzzZZzzzzZZzzz");
  }
}

class main {
  public static void main(String[] args) {
    Pig p = new Pig();  // Create a Pig object
    p.animalSound();
    p.sleep();
  }
}

Example 2

This example runs for multiple interfaces problem. There are two interfaces which are implemented by a single class.

interface InterfaceOne {
  public void Method(); // interface method
}

interface InterfaceTwo {
  public void Method2(); // interface method
}

// Demo "implements" InterfaceOne and InterfaceTwo
class Demo implements InterfaceOne, InterfaceTwo {
  public void Method() {
    System.out.println("Text One");
  }
  public void Method2() {
    System.out.println("Text two");
  }
}

class main {
  public static void main(String[] args) {
    Demo Obj = new Demo();
    Obj.Method();
    Obj.Method2();
  }
}

RELATED TAGS

java
interface
abstract
class
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring