Interface in Java
Interface in Java: Complete Beginner Guide (With Examples)
✨ Quick Summary
In this post, you’ll learn what an Interface is in Java and why it is used in OOP. We will cover interface syntax, implements keyword, multiple inheritance, and real beginner-friendly examples.
In our previous post, we learned about Abstraction and how Java hides implementation details.
Now, let’s learn another very important concept: Interface in Java.
1) What is an Interface?
An interface in Java is a blueprint of a class. It contains method declarations that must be implemented by the class.
In simple words:
- ✅ Interface tells what to do
- ❌ Interface does not tell how to do (implementation is in class)
2) Why Do We Use Interface?
Interfaces are used for:
- ✅ Achieving abstraction
- ✅ Achieving multiple inheritance
- ✅ Creating a standard structure
- ✅ Writing flexible and reusable code
3) Interface Syntax
Interface is created using the keyword interface.
interface Demo {
void show();
}
A class implements an interface using the keyword implements.
4) Example: Interface in Java
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting...");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
}
}
5) Multiple Inheritance using Interface
Java does not support multiple inheritance using classes. But Java supports multiple inheritance using interfaces.
Example
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() {
System.out.println("This is A");
}
public void showB() {
System.out.println("This is B");
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
C obj = new C();
obj.showA();
obj.showB();
}
}
6) Difference Between Abstract Class and Interface
Conclusion
Interfaces are one of the most important concepts in Java OOP. They help you achieve:
- ✅ Abstraction
- ✅ Multiple inheritance
- ✅ Clean and flexible code
In the next post, we will learn about Packages in Java and how Java organizes classes.
That’s quite an improvement.
ReplyDelete