Interface Introduction

Introduce some interface usage in Java. (This is not a comprehensive tutorial!)

What is

An interface is an abstract type that contains a collection of related methods with empty bodies and constant variables. It is one of the core concepts in Java.

Animal.java
// a self-defined interface
interface Animal {
  public void eat(); // interface method (does not have a body)
  public void moving(); // interface method (does not have a body)
  
  
  public static void main(String[] args) {
        //Animal cat = new Animal(); This is wrong
    }
}

For example,

hello.sh

public class Cat implements Animal{
    @Override
    public void eat() {
        System.out.println("Cat eats cat food!");
    }

    @Override
    public void moving() {
        System.out.println("Cat jumps, runs and walking!");
    }

    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();
        cat.moving();
    }
}

Functional Interface

A functional interface is any inteface with a single abstract method. For example, the Animal inteface is not a functional interface, but the PPrin.

Lambdas in Java 8

Llambda expressions are introduced in Java 8.

An expression in Java is an implementation of a functional interface.

Comparator Functional Interface

FrequencySort

Last updated

Was this helpful?