# Interfaces in Java

In 
Published 2022-12-23

# Interfaces in Java - explanation

Abstraction in general hide the implementation details from the user. We can see WHAT an object can do, but not HOW. Abstraction in Java is realized by using abstract classes and interfaces.

An interface class in Java is a class which:

  • define a collection of public and abstract methods (which will be implemented later)
  • could define a collection of public, static & final variables
  • (starting from Java 8) could define a default method and some static methods

# Interfaces in Java - example

Here is an interface definition:

Shape.java
public interface Shape {
    void drawShape();
    void eraseShape();
}

Here is the class which implements the interface class:

Triangle.java
public class Triangle implements Shape {

    public void drawShape() {
        System.out.println("Draw shape from Triangle Class.");
    }
     
    public void eraseShape() {
        System.out.println("Erase shape from Triangle Class.");
    }

}

Here is the code of the main class:

MyApp.java
public class MyApp {

    public static void main(String [] args) {
        Triangle triangle = new Triangle();
        triangle.drawShape();
        triangle.eraseShape();
 
    }
}