Java Interface Example

Java Interface Example


Java coding comes with three types of classes – concrete classes, abstract classes and interfaces and comes with two keywords to inherit these classes – extends and implements. This tutorial is on how to use Java Interfaces with an example.

Basically, Java does not support multiple inheritance and infact it is a drawback, says every C++ Programmer. Infact, it is avoided to avoid the confusing concept of virtual functions. To overcome this, Designers introduced interfaces.

See the following code does not work as it is an example of Java multiple inheritance.

class Bird { }
class Animal { }
public class Ostrich extends Bird, Animal { }

Interface is not completely new. After all, it is a special type of abstract class where all methods should be abstract only. Just to inform the compiler that we are using interfaces, use implements keyword.

Example on Java interfaces and implements keyword


Java Interface
Output screenshot on using Java Interface

Observe, in the above code, Ostrich inherits two interfaces using implements keyword and not extends. After Java implements there should be interfaces only of any number.

To know more on inheritance with interfaces and implements refer Java Multiple Interfaces Inheritance.

Leave a Reply

Your email address will not be published. Required fields are marked *