Table of Contents
An interface is a template for another class to follow. It defines strictly all of the abstract methods that any class that wants to implement must include. Interfaces are similar to abstract classes except that every method in an interface must be abstract, it does not contain a constructor, and it does not contain instance fields.
Declaring Instances
To declare a new instance, use the instance
keyword:
JAVApublic interface Phone {
public void call();
public void text();
}
Let's say we want to represent phones in our code. Phones can both call and text, but each phone does it slightly differently. This interface defines the methods that all phones need to do, so any class that implements this interface, will need to include their version of it.
Implementing Interfaces
Now let's create classes that implement our Phone
interface using the implements
keyword:
JAVApublic class iPhone implements Phone {
public void call() {
System.out.println("iPhone call");
}
public void text() {
System.out.println("iPhone Text");
}
}
public class Pixel implements Phone {
public void call() {
System.out.println("Pixel call");
}
public void text() {
System.out.println("Pixel Text");
}
}
Now we can create actual Phone
objects and invoke their interface methods:
JAVAPhone iPhone = new iPhone();
iPhone.call();
iPhone.text();
Phone pixel = new Pixel();
pixel.call();
pixel.text();
BASHiPhone call
iPhone Text
Pixel call
Pixel Text
And just like that, we can define multiple instances of Phone
and be guaranteed that each one will have the methods outlined in the interface.
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js