Interface in Java

Earlier we have learnt abstract class. We learnt that with abstract class we can achieve partial abstraction and with interface we can achieve 100% abstraction. Let’s see how we can achieve 100% abstraction with Interface in this post.

Abstraction is a methodology of hiding the implementation of internal details and showing the functionality to the users.

An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract. We can achieve 100% abstraction and multiple inheritance in Java with Interface.

Points to remember:

1. Java interface represents IS-A relationship similar to Inheritance
2. Interface cannot be instantiated same like abstract class
3. Java compiler adds public and abstract keywords before the interface methods
4. Java compiler adds public, static and final keywords before data members
5. Interface extends another interface just like a Class extends another Class but a class implements an interface.
6. The class that implements interface must implement all the methods of that interface.
7. Java allows you to implement more than one interface in a Class

Let’s see some example program:

To create an interface – Right click on your project – New – Interface

Now create a class and implements it with the above interface

Interface extends another interface but interface cannot implement another interface.

Now let’s see how interface extends another interface by creating two interfaces. If an interface (say MyInterfaceTwo) extends another interface (MyInterfaceOne). Now if a Class implements the interface InterfaceTwo then this class has to provide implementation of all the methods of both interfaces (MyInterfaceOne and MyInterfaceTwo)

To create an interface – Right click on your project – New – Interface

Let’s create another interface

Let’s create a Class


Must Read: Java Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Leave a Comment

Share via
Copy link
Powered by Social Snap