bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java interface Keyword

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java interface Keyword?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Order

Put the learning moves in the order that makes the concept easiest to apply.

Multiple Interfaces
Definition and Usage
Java interface Keyword

❮ Java Keywords

interface

Definition and Usage

The interface keyword is used to declare a special type of class that only contains abstract methods.

To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the "implement" class.

  • It cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass)
  • Interface methods does not have a body - the body is provided by the "implement" class
  • On implementation of an interface, you must override all of its methods
  • Interface methods are by default abstract and public
  • Interface attributes are by default public , static and final
  • An interface cannot contain a constructor (as it cannot be used to create objects)

To achieve security - hide certain details and only show the important details of an object (interface).

Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).

Multiple Interfaces

To implement multiple interfaces, separate them with a comma:

Example

interface FirstInterface {
  public void myMethod(); // interface method
}
interface SecondInterface {
  public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface, SecondInterface { public void myMethod() { System.out.println("Some text..");
}
public void myOtherMethod() {
  System.out.println("Some other text...");
}
}
class MyMainClass {
  public static void main(String[] args) {
    DemoClass myObj = new DemoClass();
    myObj.myMethod();
    myObj.myOtherMethod();
  }
}

Related Pages

Read more about interfaces in our Java Interface Tutorial .

❮ Java Keywords

Previous

Java int Keyword

Next

Java long Keyword