Зміст курсу
Java OOP
Java OOP
What is Interface?
What if we need to inherit from more than one class? Java allows us to do this with interfaces. Despite the name, an interface is very similar to an abstract class. Let's take a look at the declaration of an interface:
In simple terms, an interface is used to define methods that a class will implement. Interfaces have a distinct syntax for creation. While we used "public class className { }
" when creating a class, the syntax for creating an interface looks different:
InterfaceExample
package com.example; public interface InterfaceExample { void methodName(); String methodThatAcceptsAndReturnsString(String parameter); }
- Pay attention to the method declaration;
- We don't use access modifiers;
- We don't provide method bodies;
- There's no need to label methods as abstract since we're working within an interface;
- We don't create fields within interfaces.
Let's consider the use of an Interface
using the example of a Media Player.
We have an Interface
called MediaPlayer
which has methods play
, pause
, and stop
. Additionally, there are two classes that implement this media player interface, namely AudioPlayer
and VideoPlayer
.
MediaPlayer
AudioPlayer
VideoPlayer
public interface MediaPlayer { void play(); void pause(); void stop(); }
As you can see, we created an interface
and two classes that implement this interface. The syntax is the same as when overriding abstract methods. We have overridden each method for each class to perform its own specific function.
One of the features of interfaces is that we can implement more than one interface. Let's take a look at an example:
Vehicle
VehicleInfo
Car
package vehicle; interface Vehicle { void startEngine(); void stopEngine(); }
We have created interfaces Vehicle
and VehicleInfo
. Additionally, we've created a class Car
that implements both of these interfaces. This way, we can choose which behavior to implement in the class, which nicely complements the object-oriented programming principle of abstraction.
Working with interfaces is very convenient, and they are used extensively. In the next chapter, we will also explore the main differences between an interface and an abstract class and learn which one is better to use in practice!
Дякуємо за ваш відгук!