What is Interface in Java with Example

What is an Interface?

An interface is just like Java Class, but it only has static constants and abstract method. Java uses Interface to implement . A Java class can implement multiple Java Interfaces. All methods in an interface are implicitly public and abstract.

Syntax for Declaring Interface interface { //methods }

To use an interface in your class, append the keyword "implements" after your class name followed by the interface name.

Example for Implementing Interface class Dog implements Pet interface RidableAnimal extends Animal, Vehicle

Why is an Interface required?

To understand the concept of Java Interface better, let see an example. The class "Media Player" has two subclasses: CD player and DVD player. Each having its unique implementation method to play music.

Another class "Combo drive" is inheriting both CD and DVD (see image below). Which play method should it inherit? This may cause serious design issues. And hence, Java does not allow multiple inheritance.

Now let's take another example of Dog.

Suppose you have a requirement where class "dog" inheriting class "animal" and "Pet" (see image below). But you cannot extend two classes in Java. So what would you do? The solution is Interface.

The rulebook for interface says,

 An interface is 100% abstract class and has only abstract methods.  Class can implement any number of interfaces.

Class Dog can extend to class "Animal" and implement interface as "Pet".

Java Interface Example:

Step 1) Copy following code into an editor. interface Pet{ public void test(); } class Dog implements Pet{ public void test(){ System.out.println("Interface Method Implemented"); } public static void main(String args[]){ Pet p = new Dog(); p.test(); } }

Step 2) Save , Compile & Run the code. Observe the Output.

Difference between Class and Interface

Class Interface

In class, you can instantiate variable and create an In an interface, you can't instantiate variable and object. create an object.

Class can contain concrete(with implementation) The interface cannot contain concrete(with methods implementation) methods

The access specifiers used with classes are private, In Interface only one specifier is used- Public. protected and public. When to use Interface and Abstract Class?

 Use an abstract class when a template needs to be defined for a group of subclasses  Use an interface when a role needs to be defined for other classes, regardless of the inheritance tree of these classes

Must know facts about Interface

 A Java class can implement multiple Java Interfaces. It is necessary that the class must implement all the methods declared in the interfaces.  Class should override all the abstract methods declared in the interface  The interface allows sending a message to an object without concerning which classes it belongs.  Class needs to provide functionality for the methods declared in the interface.  All methods in an interface are implicitly public and abstract  An interface cannot be instantiated  An interface reference can point to objects of its implementing classes  An interface can extend from one or many interfaces. Class can extend only one class but implement any number of interfaces  An interface cannot implement another Interface. It has to extend another interface if needed.  An interface which is declared inside another interface is referred as nested interface  At the time of declaration, interface variable must be initialized. Otherwise, the compiler will throw an error.  The class cannot implement two interfaces in java that have methods with same name but different return type.

Summary:

 The class which implements the interface needs to provide functionality for the methods declared in the interface  All methods in an interface are implicitly public and abstract  An interface cannot be instantiated  An interface reference can point to objects of its implementing classes  An interface can extend from one or many interfaces. A class can extend only one class but implement any number of interfaces

Interface vs Abstract Class in Java: What's the Difference?

What is Interface?

The interface is a blueprint that can be used to implement a class. The interface does not contain any concrete methods (methods that have code). All the methods of an interface are abstract methods.

An interface cannot be instantiated. However, classes that implement interfaces can be instantiated. Interfaces never contain instance variables but, they can contain public static final variables (i.e., constant class variables)

What Is Abstract Class?

A class which has the abstract keyword in its declaration is called abstract class. Abstract classes should have at least one abstract method. , i.e., methods without a body. It can have multiple concrete methods.

Abstract classes allow you to create blueprints for concrete classes. But the inheriting class should implement the abstract method.

Abstract classes cannot be instantiated.

Important Reasons For Using Interfaces

 Interfaces are used to achieve abstraction.  Designed to support dynamic method resolution at run time  It helps you to achieve loose coupling.  Allows you to separate the definition of a method from the inheritance hierarchy

Important Reasons For Using Abstract Class

 Abstract classes offer default functionality for the subclasses.  Provides a template for future specific classes  Helps you to define a common interface for its subclasses  Abstract class allows code reusability.

Interface Vs. Abstract Class

An abstract class permits you to make functionality that subclasses can implement or override whereas an interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces.

Parameters Interface Abstract class

Speed Slow Fast

Multiple Implement several Interfaces Only one abstract class Inheritances

Structure Abstract methods Abstract & concrete methods

When to use Future enhancement To avoid independence

Inheritance/ The class can inherit only one Abstract A Class can implement multiple interfaces Implementation Class Parameters Interface Abstract class

While adding new stuff to the interface, it is a In case of Abstract Class, you can take Default nightmare to find all the implementors and advantage of the default Implementation implement newly defined stuff. implementation.

The interface does not have access modifiers. Abstract Class can have an access Access Modifiers Everything defined inside the interface is modifier. assumed public modifier.

It is better to use interface when various It should be used when various implementations share only method When to use implementations of the same kind share signature. Polymorphic hierarchy of value a common behavior. types.

Data fields the interface cannot contain data fields. the class can have data fields.

Multiple A class may implement numerous interfaces. A class inherits only one abstract class. Inheritance Default

An abstract class can give complete, An interface is abstract so that it can't provide Implementation default code which should be any code. overridden.

Use of Access You cannot use access modifiers for the You can use an abstract class which modifiers method, properties, etc. contains access modifiers.

Interfaces help to define the peripheral An abstract class defines the identity of Usage abilities of a class. a class.

An abstract class allows you to define Defined fields No fields can be defined both fields and constants

An interface can inherit multiple interfaces An abstract class can inherit a class and Inheritance but cannot inherit a class. multiple interfaces.

Constructor or An interface cannot declare constructors or An abstract class can declare destructors destructors. constructors and destructors.

It can extend only one class or one Limit of Extensions It can extend any number of interfaces. abstract class at a time.

In an abstract class, the abstract In an abstract interface keyword, is optional Abstract keyword keyword is compulsory for declaring a for declaring a method as an abstract. method as an abstract.

An interface can have only public abstract An abstract class has protected and Class type methods. public abstract methods.

Sample code for Interface and Abstract Class in Java

Following is sample code to create an interface and abstract class in Java

Interface Syntax interface name{ //methods }

Java Interface Example: interface Pet { public void test(); } class Dog implements Pet { public void test() { System.out.println("Interface Method Implemented"); } public static void main(String args[]) { Pet p = new Dog(); p.test(); } }

Abstract Class Syntax abstract class name{ // code }

Abstract class example: abstract class Shape { int b = 20; abstract public void calculateArea(); } public class Rectangle extends Shape { public static void main(String args[]) { Rectangle obj = new Rectangle(); obj.b = 200; obj.calculateArea(); } public void calculateArea() { System.out.println("Area is " + (obj.b * obj.b)); } }