Why would you declare an Interface and then instantiate an object with it in Java?

后端 未结 10 1330
再見小時候
再見小時候 2020-12-13 06:41

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my frie

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 07:40

    Declaring interfaces and instantiating them with objects allows for a powerful concept called polymorphism.

    List list = new ArrayList();
    list.add(new Car());
    list.add(new Bike());
    
    for (int i = 0; i < list.size(); ++i)
        list.get(i).doSomeVehicleAction();   // declared in IVehicle and implemented differently in Car and Bike
    

    To explicitly answer the question: You would use an interface declaration (even when you know the concrete type) so that you can pass multiple types (that implement the same interface) to a method or collection; then the behavior common to each implementing type can be invoked no matter what the actual type is.

提交回复
热议问题