INTERFACES – Full & Easy Notes
■ Definition:
An interface in Java is like a plan or blueprint of a class. It tells what to do, but not how
to do it. Interface only has method declarations (no body). A class that uses (implements)
the interface must write the method body.
■ Declaration of Interface:
Syntax:
interface InterfaceName {
returnType methodName();
}
Example:
interface Animal {
void eat();
void sleep();
}
■ Initialization / Implementation of Interface:
Interfaces cannot be created directly. A class must implement the interface and define its
methods.
class Dog implements Animal {
public void eat() { [Link]("Dog eats food"); }
public void sleep() { [Link]("Dog sleeps well"); }
}
class Main {
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
■ Extending Interfaces:
One interface can extend another. The new interface inherits all methods of the old one.
interface A { void show(); }
interface B extends A { void display(); }
class C implements B {
public void show() { [Link]("Showing A method"); }
public void display() { [Link]("Displaying B
method"); }
}
class Main {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
}
}
■ Multiple Inheritance using Interfaces:
Java supports multiple inheritance through interfaces. One class can implement multiple
interfaces.
interface A { void show(); }
interface B { void display(); }
class C implements A, B {
public void show() { [Link]("A’s show method"); }
public void display() { [Link]("B’s display method");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
}
}
■ Example Using Classes A, B, C, D:
interface A { void msgA(); }
interface B { void msgB(); }
class C implements A, B {
public void msgA() { [Link]("Message from Interface
A"); }
public void msgB() { [Link]("Message from Interface
B"); }
}
class D {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
}
}
■ Types of Interfaces:
Type Description Example
Single Interface Only one interface used by a class class A implements X
Multiple Interface One class implements 2 or more interfaces class A implements X, Y
Hierarchical Interface One interface extended by another interface Y extends X
Marker Interface Empty interface, used for identification Serializable, Cloneable
Functional Interface Only one abstract method Runnable, Comparable
■ Final Note:
In Java, interfaces help achieve multiple inheritance and abstraction. They make programs
more flexible, organized, and reusable. Hence, interfaces are an important concept in
object-oriented programming.