What is interface in Java? What are the differences between interface and class?

What is an interface?

In Java, an interface is similar to a class. It is a reference type with a collection of abstract methods.

What an interface contains?

An interface contains the following items:

  • abstract methods
  • constants
  • default methods
  • static methods
  • nested types

Interface usually does not contain method body. The Method bodies exist in case of default methods and static methods.

Similarities with the class

  • An interface can have any number of methods similar to a class.
  • Like java class an interface is written in a file with a .java extension
  • Similar to the java class, the name of the interface has to match with the name of the file.
  • The byte code of an interface written in a .class file which is the case of java class.

Dissimilarity with the class

  • An interface does not contain any constructors.
  • We cannot instantiate an interface.
  • All of the methods in an interface are abstract.
  • An interface is implemented by a class not extended by a class
  • Fields in an interface must be declared both static and final as it cannot contain instance fields.
ClassInterface
A class describes the attributes and behaviors of an object.An interface contains behaviors that a class implements.
A class can have abstract methods, concrete methods.An interface can have only abstract methods.
Members of a class can be public, private, protected or default.All the members of an interface are public by default.