Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
The interface keyword is used to declare an interface.
Syntax : Declare interface
interface <interface_name> {
// declare constant fields(e.g- final int a = 10;)
// declare abstract methods (e.g-void display();)<-no method body only
declaration
}
A class extends another class, an interface extends another interface, but a class
implements an interface.
class interface interface
extends implements extends
class class interface
Syntax: Implementing interface
interface Intf
{
void show(); // only declared not defined i.e abstract method
}
class Clnew implements Intf //Clnew is implementing Intf i.e inheriting
{
public void show()
{
System.out.println("Hello"); // subclass is defining the method
}
public static void main(String args[])
{
Clnew obj = new Clnew(); // object of interface can’t be created i.e
can’t be instantiated, object of subclass is created.
obj.show();
}
}
CLASS INTERFACE
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
A class can be instantiated i.e, An Interface cannot be instantiated i.e,
objects of a class can be created. objects cannot be created.
Class does not support multiple Interface supports multiple inheritance.
inheritance.
It can be inherited by another class.It cannot inherit a class.
It can be inherited by another class It can be inherited by a class by using the
using the keyword ‘extends’. keyword ‘implements’ and it can be
inherited by an interface using the
keyword ‘extends’.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can All variables and methods in a interface are
be declared using any access declared as public.
specifier (public, private, default,
protected)
Variables in a class can be static, All variables are static and final.
final or neither.