[Solved] Why we defines the Interfaces in Java, The core reason and advantages of defining an interface? [closed]


Interfaces let you define methods that will be common to a group of classes. The implementation of the interface can be different for each class, and it’s up to those classes to independently implement what that methods do.

interface Animal {
    // Define the interface
    Boolean canBite();
}

class Dog implements Animal {
    // Define an implementation for Dog
    @override
    public Boolean canBite() {
        return true;
    }
}

class Duck implements Animal {
    // Define an implementation for Duck
    @override
    public Boolean canBite() {
        return false;
    }
}

class Program {
    public static void main(String[] args) {
        // Create an array of the interface type and populate it with examples
        Animal[] animals = new Animal[4];
        animals[0] = new Dog();
        animals[1] = new Duck();
        animals[2] = new Duck();
        animals[3] = new Dog();

        // Check which members can bite
        for (Animal animal : animals) {
            System.out.println(animal.canBite());
        }
    }
}

/*
 * Output:
 * true
 * false
 * false
 * true
 */

4

solved Why we defines the Interfaces in Java, The core reason and advantages of defining an interface? [closed]