栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-03

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-03

啃某项目代码的时候,发现接口也被引用到了类内部。具体如下:

public interface CommonError {

    public int getErrCode();
    public String getErrMsg();
    public CommonError setErrMsg(String errMsg);

}

public class BusinessException extends Exception implements CommonError{
    private CommonError commonError;
}

接口不是不能被实例化吗?接口必须要被类实现才可以实例化,那么这个引用怎么回事。类在使用的时候,会使用new关键字来创建对象,而接口在使用的时候不能被new。接口在做引用类型的时候,依靠的是实现接口的类。

public interface Animal {
    public void eat();
}

public class Cat implements Animal {
    @Override
    public void eat() {
        System.out.println("Cat eat");
    }
}

public class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("Dog eat");
    }
    
}

public class Zoo {
    private Animal animal;
    public void eat(Animal animal){
        this.animal = animal;
        animal.eat();;
    }
    public void test(){
        System.out.println("接口引用调用:");
        animal.eat();
    }
}

声明一个Animal类,两个实现类Cat和Dog,在Zoo类中将接口引用。Zoo中的引用animal是必须要依靠实现类的,必须先给Zoo中的animal指定它的实现类,才能够调用接口方法,否则会出现空指针异常,因为并不知道实现类在哪里。

public class Test {
    public static void main(String[] args) {

        Cat cat = new Cat();
        Dog dog = new Dog();
        Zoo zoo = new Zoo();
        zoo.eat(cat);
        zoo.test();

        System.out.println();
        zoo.eat(dog);
        zoo.test();
    }
}

运行结果:
Cat eat
接口引用调用:
Cat eat

Dog eat
接口引用调用:
Dog eat

如果将上述的this.animal = animal注释掉,程序出现空指针异常。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号