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.
// 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
}
}An interface can not be used for instantiating an object. It has to be implemented by a class type first.
For example,
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.
A Lambda expression is an expression that should reside in a code body.
Syntax:
Comparator Functional Interface
FrequencySort
Last updated
Was this helpful?