Java Interface


In Java, an interface helps to achieve an abstraction. An interface contains only a declaration.

 

An interface consists of abstract methods and final variables.

 

Multiple inheritance is not supported in java. But we can achieve multiple inheritances through an interface.

 


Syntax:

interface interface_name1{
	// declare constant fields  
    // declare methods that abstract 
}
interface interface_name2{
	// declare constant fields  
    // declare methods that abstract 
}
class class_name implements interface_name1,interface_name2{
	// fields  
	// methods 
} 

Example:-

 interface Roll
{
	int rollno = 10;  
}
interface Name
{
	String name = "Sundarrajan"; 
	void showdata();  
}
class Student implements Name,Roll
{ 	
	public void showdata()
    {
    	System.out.println(rollno+" "+name); 
	} 
} 
public class Interface{  
    public static void main(String args[])
    {  
        Student s1=new Student();
        s1.showdata(); 
    }
}

Difference between Abstract Class and Interface.

Abstract Class Interface
An abstract class can have both declaration and definition. An interface can have declaration only.
Does not support multiple inheritance. Supports multiple inheritance.
An abstract class has final, non-final, static and non-static variables. An interface has static and final variables.
To declare an abstract class using abstract keyword. To declare an interface using interface keyword.
An abstract class can extend another class. An interface can extend another interface.
An abstract class can have both abstract and non-abstract methods. The interface has abstract methods only.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.