Sub topic 6
Declaring an Interface
What Is an Interface?
An interface is a Java type that lists methods a class promises to have. It says what a type can do. It does not say how it does it.
You have already seen abstract classes. An abstract class can mix finished methods with abstract methods. An abstract method is a method with a name, parameters, and a return type, but no body. An interface is a purer kind of promise. In its simplest form, it holds only abstract methods.
Think of a wall socket. The socket has a fixed shape. Any plug with that shape works, whether it belongs to a lamp, a phone charger, or a fan. The socket does not care what the device does inside. An interface plays the role of the socket's shape in your code.
The Basic Syntax
You declare an interface with the keyword interface instead of class.
public interface Playable {
void play();
void stop();
int volume();
}Each part does this job:
publicis an access modifier. It lets code in any package use the interface.interfacetells Java this is an interface, not a class.Playableis the interface's name.void play();is an abstract method. It ends with a semicolon. It has no curly braces and no body.
Like a public class, a public interface must live in a file with the same name. This one goes in Playable.java.
Hidden Words: Implicit Modifiers
A modifier is a keyword such as public or abstract that changes the meaning of a declaration. In an interface, Java adds some modifiers for you. These are called implicit modifiers.
Every method you write without a body inside an interface is automatically public and abstract. So these two interfaces mean exactly the same thing:
interface Greeter {
void greet(String name);
}
interface GreeterLongForm {
public abstract void greet(String name);
}Most Java programmers use the short form. Writing public abstract is legal, but it adds noise.
What an Interface Cannot Have
An interface is not a class, so some things are not allowed:
| Feature | Abstract class | Interface |
|---|---|---|
| Abstract methods | Yes | Yes |
| Constructors | Yes | No |
| Instance fields (per-object data) | Yes | No |
| Create an object with `new` | No | No |
| Method access when you write no modifier | Package-private | Public |
An instance field is a variable that each object holds its own copy of, like radius in a Circle. An interface cannot store per-object data, so it has no constructor to set that data up.
You also cannot create an object from an interface directly:
Playable p = new Playable(); // compile error: Playable is abstractThe interface is only a promise. Something has to keep the promise first.
Seeing the Shape of an Interface
The plus signs mean the methods are public. The dashed arrow means "this class fulfills that interface." The next chapter covers how a class does that.
A Complete Runnable Example
To run any code, some class has to keep the interface's promises. The next chapter covers the implements keyword fully. Here you only need a tiny preview so the program can run. Save everything in one file called Main.java:
interface Playable {
void play();
void stop();
int volume();
}
class MusicTrack implements Playable {
private final String title;
MusicTrack(String title) {
this.title = title;
}
@Override
public void play() {
System.out.println("Playing " + title);
}
@Override
public void stop() {
System.out.println("Stopped " + title);
}
@Override
public int volume() {
return 7;
}
}
public class Main {
public static void main(String[] args) {
Playable track = new MusicTrack("Morning Song");
track.play();
System.out.println("Volume: " + track.volume());
track.stop();
}
}Compile and run it:
javac Main.java
java MainThe output is:
Playing Morning Song
Volume: 7
Stopped Morning SongLook at the interface Playable line. It has no public, because only one top-level type in a file may be public, and here that type is Main. An interface without public is package-private, which means only code in the same package can use it. That is fine for a small example.
Note too that the methods in MusicTrack are marked public. The interface methods are secretly public, so the class must keep them public.
Common Beginner Mistakes
- Giving an abstract method a body. Writing
void play() { }inside an interface fails to compile. Java says interface abstract methods cannot have a body. Use a semicolon instead. - Forgetting the semicolon.
void play()with nothing after it is a syntax error. - Adding a constructor.
Playable() { }inside an interface does not compile. Interfaces have no constructors. - Trying to use
newon the interface. You need a class that keeps the promise. - Mismatched file name. A
public interface Playablemust be inPlayable.java.
Why Declare an Interface at All?
An interface lets you write code that depends only on the promise. A method that takes a Playable works with a music track, a video, or a podcast, as long as each keeps the same three promises. You can add new kinds of playable things later without changing that method. This idea, called programming to a type, comes back throughout the rest of this tutorial.
Exercise
Write an interface named Measurable with two methods: one named length that takes no parameters and returns a double, and one named unit that takes no parameters and returns a String.
Show answer
interface Measurable { double length(); String unit(); } Each method ends with a semicolon and has no body. Java adds public and abstract to both methods for you.
Exercise
A student writes this inside an interface: private void reset(); Why does it fail to compile?
Show answer
An abstract method in an interface is always public. Marking it private conflicts with that, so the compiler rejects it. Remove the private keyword.
Exercise
Is the line Measurable m = new Measurable(); legal? Explain.
Show answer
No. Measurable is an interface, which means it is abstract, so you cannot create an object from it with new. You need a class that implements Measurable, and then you can write something like Measurable m = new Ruler();
Exercise
Name two things an abstract class can contain that a simple interface cannot.
Show answer
Constructors and instance fields (data stored separately in each object). An interface holds neither.