Interface in java — Java Technical Interview Questions & Answers

Interface in java

Interface in java

  • An interface is a contract: if you implement me, you must provide these behaviours. class Circle implements Drawable. A class can implement many interfaces — multiple capabilities.
  • Good names sound like abilities: Runnable, Comparable, Drawable. Modern Java can add default and static methods, but the core idea is still the contract: what you can do, not a family of shared fields.
  • If you mainly need shared fields and shared code, consider an abstract class. Interview line: interface = can-do contract; a class may implement many.
  • Let's take this on the board with one tiny Main class — no extra files. Interface in java — output: Draw circle. Drawable d = new Circle() is allowed — interface type, real Circle object. Start from main, go line by line, and stop at each print. That output is the proof for Interface.
  interface Drawable
    draw()
         │ implements
         ▼
      Circle.draw()

Technical Interview Tip: Multiple interfaces vs single superclass.

Code Examples for Interface in java

Example

interface Drawable {
  void draw();
}
class Circle implements Drawable {
  public void draw() { System.out.println("Draw circle"); }
}
public class Main {
  public static void main(String[] args) {
    Drawable d = new Circle();
    d.draw();
  }
}

Interface in java — output: Draw circle. Drawable d = new Circle() is allowed — interface type, real Circle object.

How to Explain Interface in java to an Interviewer

What is an interface?

A contract of behaviours

How many interfaces can a class implement?

Many

What keyword is used?

implements