Interface in Java

An interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. It is a blueprint of class. Unlike the class, it contains only public & abstract methods and public, static & final fields.

One or more classes can implement a defined interface in java.When a class implements a defined interface, it has to implement (write the code, execution logic) for all the methods defined by the interface. The class is free to define more methods if necessary.Interface Implementation
 

Interface Syntax:

Example:

Difference between Interface and Class:

Interface Class
Have only abstract methods Cannot have abstract method
Multiple Inheritance possible Multiple Inheritance not possible
Can not be instantiated Can be instantiated
Do not have constructors Have constructor

Some facts about Interface:

  • Interface is used to achieve loose coupling
  • Multiple inheritance can be achieved by using interface
  • Interface provides full abstraction
  • Interface can extend multiple Interfaces
  • An interface does not contain any constructors, that is why Interface cannot be instantiated

InterfaceClass

MainClass

  • JVM itself writes the public static final before the data members and public abstract before methods in Interface if programmer does not write it

For Example:

Interfaces are similar to abstract classes, but the differences between them are as follows:

  • All methods in an interface are abstract, which means all methods must be empty while in abstract classes no code is implemented
  • In an abstract class, the methods can have code/implementation within it but in abstract class, at least one method must be abstract
  • All properties (data fields) in an interface are static final while properties in an abstract class need not be static final
  • Interfaces are implemented(implements keyword) on the other hand Abstract classes are extended(extends keyword)
  • Class can extend only one abstract class whereas a class can implement multiple interfaces (multiple inheritance)
  • Contractual obligation: When a class specifies that it implements an interface, it must define all methods of that interface.

Complete Example Of Implementation Of Interface:

Github
For more Complete Examples on this topic visit codedbug Git Repository
 

1 thought on “Interface in Java

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?