Interfaces

Interfaces are "classes" in which, by default, all fields are public, static, and final, and methods are public and abstract. A class can't inherit from multiple classes but can implement multiple interfaces. It is mandatory to implement (override) all of the interface's methods. Interface methods can't contain any implementation, providing only method signatures that must be implemented by subclasses. We create interfaces using the interface keyword. Interfaces are used as templates for classes, ensuring a consistent structure. For example, when implementing an interface in a graphical window application, the method responsible for creating the window must be provided, or the application will not function properly.


import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        System.out.println(Interface.PI);

        Interface x = new Worker(2000);
        System.out.println(((Worker) x).getSalary());

        Worker[] worker = new Worker[3];
        worker[0] = new Worker(4000);
        worker[1] = new Worker(10000);
        worker[2] = new Worker(2000);
        Arrays.sort(worker, Collections.reverseOrder()); // the second argument is not mandatory
        for (Worker w: worker)
            System.out.println(w.getSalary());
    }
}

interface Interface {
    double PI = 3.14;
    void method();
}

class Worker implements Interface, Comparable {
    @Override
    public void method() {}

    private double salary;
    Worker(double salary) {this.salary = salary;} // inline method (intended for short operations)
    public double getSalary() {return this.salary;}

    @Override
    public int compareTo(Object o) {
        Worker sent = (Worker) o;
        if (this.salary < sent.salary)
            return -1;
        else if (this.salary > sent.salary)
            return 1;
        return 0;
    }
}
                                    

Default methods

If we don't want to be forced to implement certain methods of an interface, we can set them as default.


public class Main {
    public static void main(String[] args) {
        Maths m = (int x) -> {
            return 5;
        };

        System.out.println(m.calculate(4));
        System.out.println(m.sqrt(2));
    }
}

interface Maths {
    double calculate(int x);
    default double sqrt(int x) {
        return Math.sqrt(x); // we don't have to import the Math class
    }
}

class Examplee implements Maths {
    @Override
    public double calculate(int x) {
        return 0;
    }
}