MCAWALA

Java Vertical Menu

Java Interface क्या है? – आसान हिंदी में पूरी जानकारी

Java Interface एक special type की class होती है जो केवल abstract methods (method signatures) को declare करती है। इसका इस्तेमाल हम एक contract की तरह करते हैं, जिसे कोई class implement करती है। यह Java की Object-Oriented Programming (OOP) का एक महत्वपूर्ण हिस्सा है।

Interface क्यों जरूरी है?

Interface का मुख्य उद्देश्य है multiple inheritance को support करना और loosely coupled design बनाना। Java में class केवल एक ही class को extend कर सकती है, लेकिन multiple interfaces को implement कर सकती है। इससे flexibility और modularity बढ़ती है।

Java Interface की खासियतें:

  • सिर्फ abstract methods होते हैं (Java 8+ में default और static methods भी हो सकते हैं)।
  • Variables हमेशा public, static, और final होते हैं।
  • कोई object interface का नहीं बनाया जा सकता।
  • किसी class को interface implement करना पड़ता है।
  • Multiple interfaces को एक साथ implement किया जा सकता है।

Interface का Syntax

interface Vehicle {
    void start();
    void stop();
}

Interface Implement करने वाला Class

class Car implements Vehicle {
    public void start() {
        System.out.println("Car started");
    }
    public void stop() {
        System.out.println("Car stopped");
    }
}

Example: Interface का उपयोग

interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Barks");
    }
}

class Cat implements Animal {
    public void sound() {
        System.out.println("Meows");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.sound();  // Output: Barks

        Animal cat = new Cat();
        cat.sound();  // Output: Meows
    }
}

Interface के फायदे:

  • Multiple inheritance को सपोर्ट करता है।
  • Loose coupling बनाता है, जिससे code maintain करना आसान होता है।
  • Code modular और reusable होता है।
  • Standard protocols या contracts बनाना आसान होता है।

निष्कर्ष

Java Interface एक powerful feature है जो program को modular, flexible और maintainable बनाता है। Interface के ज़रिए हम code में loosely coupled design ला सकते हैं और multiple inheritance की समस्या को हल कर सकते हैं। Beginners के लिए Interface सीखना OOP समझने का एक महत्वपूर्ण कदम है।