啃某项目代码的时候,发现接口也被引用到了类内部。具体如下:
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注释掉,程序出现空指针异常。