Learning Java: Interfaces

Ifeoluwa Akinremi Wade
2 min readMay 18, 2022

One of the most interesting things about Java is Java interface. Because Java is a Object Oriented Programming language, classes are often used in code. In regards to inheritance, Java classes aren’t supposed to inherit from multiple classes. This is where an interface comes in.

What Is Interface?

An interface “is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface… a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements” (Java — Interfaces).

Why?

As I mentioned above, there multiple inheritance is not a thing. A class can only inherit from one superclass (parent class). Secondly, Interface are used for security purposes. Because interfaces are a collection of abstract methods, methods without bodies, only certain details of an object can be on display.

Interface Is An Abstract Class

interface Flower {
public void bloom(); // interface method (does not have a body)
public void color(); // interface method (does not have a body)
}

All interface classes must begin with the keyword interface. Within the body of the class, there can be on to multiple abstract methods — no body.

Because an interface is an abstract class, it is cannot be used to create objects.

Implement or Inherit, Tomato Tomahto

When a class “inherits” from an interface in order to gain access to the interface methods, it implements it.

interface Flower {
public void bloom(); // interface method (does not have a body)
public void color(); // interface method (does not have a body)
}
class Aster implements Flower {
public void bloom() {
// The body of bloom() is provided here
System.out.println("Late Spring");
}
public void color() {
// The body of color() is provided here
System.out.println("white, pink, red, orange, yellow, or purple");
}
}

A class that will implement an interface will use the implement keyword.

Multiple Interface

Above, I mentioned that in Java a class can only inherit from one superclass; However, a class can implement multiple interfaces separated by commas.

class Aster implements Flower, interface2, interface3 {
public void bloom() {
// The body of bloom() is provided here
System.out.println("Late Spring");
}
public void color() {
// The body of color() is provided here
System.out.println("white, pink, red, orange, yellow, or purple");
}
}

--

--