Interface in Java
What is an Interface?
An interface in Java is a contract that defines abstract methods which a class must implement. It provides 100% abstraction and allows multiple inheritance.
Java में interface एक contract होता है जिसमें abstract methods की definition होती है जिन्हें implementing class को implement करना जरूरी होता है। यह 100% abstraction और multiple inheritance को support करता है।
Why Use Interface?
- To achieve abstraction.
- To support multiple inheritance.
- To define a standard contract.
- To decouple code and make it more flexible.
- Abstraction को achieve करने के लिए।
- Multiple inheritance को support करने के लिए।
- एक standard contract define करने के लिए।
- Code को loosely coupled और flexible बनाने के लिए।
Advantages of Interface
- Provides 100% abstraction.
- Supports multiple inheritance.
- Promotes loose coupling.
- Makes code flexible and testable.
- 100% abstraction provide करता है।
- Multiple inheritance को support करता है।
- Loose coupling को बढ़ावा देता है।
- Code को flexible और testable बनाता है।
Example: Employee Class Implementing Multiple Interfaces
In this example, Employee
implements two interfaces: Workable
and Payable
. This demonstrates multiple inheritance in Java.
इस उदाहरण में Employee
class दो interfaces implement करती है: Workable
और Payable
। यह Java में multiple inheritance को दिखाता है।
interface Workable {
void work();
}
interface Payable {
void pay();
}
class Employee implements Workable, Payable {
public void work() {
System.out.println("Employee is working on assigned tasks.");
}
public void pay() {
System.out.println("Employee is getting salary.");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Employee emp = new Employee();
emp.work();
emp.pay();
}
}
Output:
Employee is working on assigned tasks. Employee is getting salary.
This shows how an interface in Java can enforce a contract while allowing classes to implement multiple behaviors through multiple interfaces.
यह दिखाता है कि Java में interface कैसे एक contract enforce करता है और classes को multiple behaviors implement करने की सुविधा देता है।
← Previous:java polymorphism Next: java exception handling →