what is the actual use of interface in java? [duplicate]

Interfaces allow you to use classes in different hierarchies, polymorphically.

For example, say you have the following interface:

public interface Movable {
    void move();
}

Any number of classes, across class hierarchies could implement Movable in their own specific way, yet still be used by some caller in a uniform way.

So if you have the following two classes:

public class Car extends Vehicle implements Movable {
    public void move() {
       //implement move, vroom, vroom!
    }
}

public class Horse extends Animal implements Movable {
    public void move() {
       //implement move, neigh!
    }
}

From the perspective of the caller, it’s just a Movable

Movable movable = ...;
movable.move();  //who am I?

I hope this helps.

Leave a Comment