使用接口类型实例化实现接口的类对象

ant*_*009 0 java

使用接口作为类型来实例化类对象有些困惑.为什么我们需要将接口作为一种类型?什么时候我们可以使用这个类?因为该类实现了接口.我知道你无法实例化一个接口.

非常感谢任何建议,

   public interface SortRecords {
        int query(int rowId);
    }

    public class OurPrice implements SortRecords {
        @Override
        public int query(int rowId) {
            return 0;
        }
    }

    public void test() {
        /* 
         * Why has the interface as the type? 
         */
        SortRecords sorterV1 = new OurPrice();
        sorterV1.query(1);

        /* 
         * Why not just do like this? 
         */
        OurPrice sorterV2 = new OurPrice();
        sorterV2.query(2);
    }
Run Code Online (Sandbox Code Playgroud)

Bri*_*new 5

界面声明合同,并为您提供指定提供相同合同的任何其他类的自由.因此,引用该接口的代码与您提供的实现无关.

在上面的例子中,它并不是特别有用.但是,在更广泛的背景下,工厂可以为您提供它喜欢的任何实现(甚至在运行时变化).作为消费者,您不必担心.您只需使用它提供的界面和合同(方法)进行通信.