+91 81900 98289

Java Interface

An interface lists methods a class promises to provide. A class can implement several interfaces. It can extend only one class. That is why interfaces are how Java shares a capability across unrelated types.

Name an interface for the capability: Readable, Payable, or Scorer. The implementing class keeps its own fields. The interface does not hold object state in the classic form.

Example

Desk fulfills Greeting. The variable type is the interface, and the object is a Desk.

interface Greeting { String hello(); } class Desk implements Greeting { public String hello() { return "Welcome"; } } public class Front { public static void main(String[] args) { Greeting g = new Desk(); System.out.println(g.hello()); } }
Interface methods are public. The implementing method must be public too. Leaving off public is a compile error.