In this interface in java tutorial, we will learn why to use interface and how to declare java interface.
What is Java Interface
It is just like a class in java, which includes abstract method. It includes abstract method (method without definition), so we can’t create object of an interface. It is always behave like a super class in java and can implements in a sub class. When an interface is implemented in a sub class, all the methods of interface must be override in sub class. It provide facility of multiple inheritance to the java.
How to create an interface
We can create an interface in java using interface keyword. After that we can use interface using implements keyword in a class.
//creating interface
interface Shape
{
//method of interface must be without body
public void area();
}
//implementing an interface
class Circle implements Shape
{
//overriding method of interface in sub class
public void area()
{
System.out.println("Area of Circle");
}
public static void main(String args[])
{
//creating object and calling method
Circle c=new Circle();
c.area();
}
}
Some Points about interface
- An interface can implements in more than one class.
- A class can implements multiple interface at a time.
- A class can extends another class and can implements multiple interface.
- An interface can have data member also but they are final by default.
- All the members of interface are always abstract and public.
Implementing Multiple Interface
We can implement multiple interface in a class. Example of implementing multiple interface.
interface A
{
//members of Interface A
}
interface B
{
//members of Interface B
}
class Test implements A, B
{
//override methods of A
//override methods of B
}
Extending a Class and Implementing an Interface
In Java, we can extends a class and can implements an interface at time. It provide facility of multiple inheritance to the Java.
interface A
{
//members of Interface A
}
class Test
{
//members of class
}
class Demo extends Test implements A
{
//override methods of A
//Use members of class Test
}