Interface with examples

Java » Interface with examples

An interface may consist of constants, default methods, abstract methods (without body )and static methods. It explains what a class should do and look like, but not how. It can be extended by other interfaces using ‘ extends’ and implemented by other classes using ‘implements’ keyword.
It cannot be instantiated, further, the class that implements it must provide the body for the implemented abstract method, otherwise, compiler triggers an error. An interface is followed by ‘interface’ keyword.

  • Java doesn’t provide support for multiple inheritance, but it is possible between Interfaces.
  • An interface can have an object, but it can’t be instantiated.
  • It doesn’t allow constructors.
  • It can be extended by other interfaces using ‘extends’ keyword.
  • It can be implemented by other classes using ‘implements’ keyword.

If no modifier is mentioned, then the interface would only be accessed within a package.

Interface having method signatures

In an interface, you can define an abstract method, and that method must be overridden by the class that implements it. In other words, A class which implements an interface must define the body of that abstract method.

Program:

Output:

By default, a compiler treats a method within an interface like this:

 

Interface having constant

Interface also allow us to declare constants whose declaration and initialization takes place at a single statement.

Program:

Output:

By default, a compiler treats a variable as constant within an interface like this:

Interface having a static method

A static method doesn’t depend upon the instance of a class. Therefore, it executes independently.

Program:

Output:


You must be logged in to take the quiz.

error: Content is protected !!