0
0
JavaHow-ToBeginner · 3 min read

How to Implement Interface in Java: Syntax and Example

In Java, you implement an interface by using the implements keyword in your class declaration and then providing concrete implementations for all the interface's methods. This allows your class to follow the contract defined by the interface.
📐

Syntax

To implement an interface in Java, declare your class with the implements keyword followed by the interface name. Then, provide method bodies for all abstract methods declared in the interface.

  • interface InterfaceName: Defines method signatures without bodies.
  • class ClassName implements InterfaceName: Class promises to implement all interface methods.
  • All interface methods must be implemented in the class.
java
interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Woof");
    }
}
💻

Example

This example shows an interface Animal with a method sound(). The class Dog implements this interface and provides the method body. When run, it prints the dog's sound.

java
interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound();
    }
}
Output
Woof
⚠️

Common Pitfalls

Common mistakes when implementing interfaces include:

  • Not implementing all methods declared in the interface, which causes a compile error.
  • Forgetting to use public access modifier on implemented methods, since interface methods are implicitly public.
  • Trying to instantiate an interface directly, which is not allowed.
java
/* Wrong: Missing method implementation */
interface Animal {
    void sound();
}

class Cat implements Animal {
    // Error: sound() method not implemented
}

/* Correct: Implement all methods with public modifier */
class Cat implements Animal {
    public void sound() {
        System.out.println("Meow");
    }
}
📊

Quick Reference

ConceptDescription
interfaceDefines method signatures without bodies
implementsKeyword used by a class to implement an interface
method implementationClass must provide bodies for all interface methods
access modifierImplemented methods must be public
instantiationCannot create objects of an interface directly

Key Takeaways

Use the implements keyword in your class declaration to implement an interface.
Provide public method bodies for all methods declared in the interface.
You cannot instantiate an interface directly; instantiate the implementing class instead.
Missing any interface method implementation causes a compile-time error.
Interface methods are implicitly public, so implementations must be public.