Interface methods in Java

(Last Updated On: March 5, 2019)

Learn all about methods in interface in java with very simple code example and explanation.

Interface in java contains only declaration of methods as shown below in interface example. All the methods in an interface are by default public and abstract and they cannot have definition or implementation.

Even though, if you don’t write public and abstract before methods, the compiler will by default treat them as public and abstract. In above example, we have not declare methods f1(), f2() and f3() public and abstract.

So for, you understand that methods in an interface do not have implementation. Meaning, it does not have body.

Now, you might be wondering, what is the use of unimplemented methods?

Answer is, all methods of interface are implemented by the classes who inherit and implement the interface.

FOCUS:

  • All methods of an interface must be overridden and implemented by the classes who implement the interface.
  • Abstract keyword before methods forces the sub classes / derived classes in inheritance relationship in java to implement interface methods. If you miss any method implementation in subclass, the compiler will throw an error.

 

Lets understand how we can write methods in an interface in java and how to inherit and implement those abstract methods by classes.

Example of Interface methods in Java

In below java code example, there is an interface “Screen” having two methods unimplemented methods i.e. LED() and LCD. There is a class TV that will implement the interface Screen. TV class will override and implement both abstract methods.

 

 

Output:
TV has LED Screen
TV has LCD Screen

 

Exercise on Interface methods in Java

You can do the following exercise on interface method in java programming to polish your knowledge.

Exercise: Create a Shape interface having method area () and perimeter (). Create a sub class Circle and Rectangle and implement those methods. Write test program to demonstrate the area and perimeters of shapes.