i

JAVA Complete Course

Defining and Implementing An Interface

An interface in java is a reference type. It is similar to class. It is a collection of abstract methods. Class can implement an interface, which means that in that case it will inherit the abstract methods of the interface. In interfaces we cannot have instance variables but we can static final variables. Prior to Java 8, interfaces didn’t support default implementation of method but after Java 8, we can give default implementation to any interface method with keyword default.

As we have already mentioned, interfaces are similar to classes. But class cannot extend interface, it only implements interface.

One class can implement multiple interfaces. Interface can extend another interface(s).

Similarities between interfaces and classes:

  • An interface can contain as many methods as user wants.

  • An interface like a class is written in .java file, with the name of the interface matching the name of the file.

  • Like the class, the byte code of an interface will appear in a .class file.

  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

Differences between interfaces and classes:

  • Interface can’t be instantiated

  • Interface does not contain a constructor

  • All of the methods of interface are abstract.

  • Interface cannot contain the fields

  • The fields which can be in interface must be declared both static and final.

  • Class cannot extend interface, it only implements interfaces

  • Interface itself can extend more than one interfaces

Let’s visit few coding examples regarding interfaces:

Extending interfaces