An interface in java is a blueprint of a class. It has static constants and abstract methods only. The interface in java is a mechanism to achieve full abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve full abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
1. It is used to achieve full abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
Note: The java compiler adds public and abstract keywords before the interface methods. The java compiler adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default, and methods are public and abstract.
Notice that, a class extends another class, an interface extends another interface but a class implements an interface.
Note: To create interface we use interface keyword.
Following code demonstrates a simple interface :
interface Printable
{ void print();
}
class A4 implements Printable
{ public void print()
{ System.out.println("Hello");
}
public static void main(String args[])
{ A4 obj = new A4();
obj.print();
}
}
Note: The child class of interface must define all methods of interface, otherwise the class must be created as abstract.
www.tarunsir.com
www.cinstitute.org.in
Connect me on linkedin
/ tarrunverrma
Connect me on instagram
/ the_ultimate_coding_stuff
Follow me on twitter
/ tarrunverrma
Join my telegram channel
t.me/tarunvermasir
#tarunsir #javatutorial #learnprogramming #coding #java #interface