Interface in java with example

In previous post, we have seen abstract class in java which provides partial abstraction. Interface is one of the core part of java and is used to achieve full abstraction.
Interface is generally used to provide contract for class to implement. Interface do not have implementation of any method.A class implements an interface, thereby inheriting the abstract methods of the interface. So it is kind of signing a contract, you agree that if you implement this interface, then you have to use its methods.It is just a pattern, it can not do anything itself.

All the methods in the interface are by default public and abstract and all variables are public static final.

Syntax for interface in java:

For example:
Let’s say you have Room class as your pojo class. Now you want all your rooms to be decorable,┬áso you can just implement decorable interface and implement decorate method.

Interface and inheritance:

You can create inheritance in terms of interface too. An interface can only extend(extends) another interface.

Important points about interface in java:

  • You need to use “Interface” keyword to declare an interface.
  • An interface can not have any method implementation.
  • Interface methods are by default public abstract.
  • Interface variables are by default public static final.
  • implements keyword is used by class to use interface.
  • One interface can not extend another class bit can extend another interface using extends keyword.
  • A class needs to override all methods of interface unless it is abstract class, otherwise, you will get compilation errors.
  • You need to design interface very carefully, as once you have used in business logic, you won’t be able to remove or add methods from interface.

Example:

Let’s create an interface called Room.java.

Create class named “SimpleRoom”

Create class named “SpecialRoom”

Create main class named “RoomInterfaceMain”

When you run above program, you will get below output:

Showing simple room
=================
Showing special Room

Java 8 interface:

There were major changes done JDK 8 in interface.You can read more about at Default method in java 8.

That’s all about interface in java.

No Responses

Add Comment