What is an Interface in Java?
An interface is a blueprint of a class that contains:
abstract methods (by default)
constants (public static final)
It is used to achieve 100% abstraction (before Java 8).
Syntax of Interface
interface InterfaceName {
// variables (constants)
int x = 10; // public static final (by default)
// abstract methods
void show(); // public abstract (by default)
}
class A implements InterfaceName {
public void show() {
[Link]("Implemented method");
Scope / Access Rules of Interface
Interface itself
Modifier Allowed?
public Yes
default Yes
Not
allowed
private
(top-
level)
Not
protected
allowed
Methods inside interface
Modifier Allowed?
Modifier Allowed?
public (default)
( only inside
private
interface)
protected ❌
default ✅
static ✅
Variables inside interface
Always:
public static final
Key Rules
Interface cannot have:
constructors
instance variables
Interface can have:
abstract methods
default methods
static methods
Class must:
use implements
override all methods
Example
interface p1
{
//public static final int x=10;
public void show();//abstract method
interface p2
public static final int y=20;
public void show();//abstract method
interface p12 extends p1,p2//we can do multiple inheritance through interface
public void display();//abstract method
class P3 implements p12//implementation of interface
public void show()
[Link]("Solve diamond problem");//override the show() method
public void display()
[Link]("this is p12");//override the display() method
}
}
class Qs2
public static void main(String[ ] args)
P3 p= new P3();
[Link]();
[Link]();
[Link](p1.x);