Java Interfaces

What is an interface in Java ?

 

Interfaces define a contract that an implementing class must agree to.

 

If a class implements an interface, it must provide implementation of all the methods or define itself as abstract.

 

Interfaces provide an way of using multiple inheritance in java since a class can extend only one other class, but it may implement any number of interfaces.

 

Here are some of the rules regarding Interfaces :

 

– A class can extend only one class, but it can implement multiple interfaces.

– Methods in interfaces are implicitly abstract and their scope is public. Since they are abstract and need to be overridden, they can not be final.

– Interface methods can not be static

– Interface variables are public, static and final. That means variables in interfaces are basically constants.

– Interface can extend one or more interfaces. Interface cannot extend a class and it can not implement a class/interface as well.

– Interfaces are implicitly abstract. So, although its redundant, you can add abstract to the interface declaration as well

– A class implementing an interface can itself be abstract.

Example

 

Here is a sample interface that provides signature for a printText() method.

package com.javatutorial;

public interface TestInterface {
  public void printText(String name);
}


 

Now any class implementing this interface has to provide implementation for the printText() method.

 

We can implement it as follows :

package com.javatutorial;

public class Hello implements TestInterface {

  public static void main(String[] args) {
    Hello h =new Hello();
    h.printText("user");
  }

  @Override
  public void printText(String name) {
    System.out.println("Hello "+ name);
  }

}

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags