LLL

java有关应该用接口类型还是实现类的类类型去引用对象相关

有 N 人看过

学习spring的时候看到这么一篇文章

https://zhuanlan.zhihu.com/p/64001753

其中介绍“开关原则”时不太明白java接口类型引用对象相关知识,学习相关知识后记录一下。

我们假设有一个接口A ,和它得实现类B,如下:

public interface InterA{

    void request();
}

public class ImplA implements InterA {

    @Override
    public void request() {
        System.out.println("接口中的方法");
    }

    public void specile() {
        System.out.println("实现类中特殊的方法");
    }
}

测试类:

public class Test {

    public static void main(String[] args) {
        /**
         * 接口类型的引用变量A 去接收对象地址,只能调用接口中的方法
         */
        InterA a= new ImplA();
        a.request();

        /**
         * 类类型的引用变量A 去接收对象地址,可以调用很多方法
         */
        ImplA b = new ImplA();
        b.request();
        b.specile();
    }
}

注释内容这就是这两种方案引用对象的区别了。