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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.