转自https://blog.csdn.net/weixin_42295141/article/details/81058327
谈到面向接口编程,我第一个要提的是java的多态。
首先,什么是多态,多态的定义:
-
//创建父类对象的时候,赋予其子类的对象
-
Father father =
new Son();
-
//调用结果是表现出子类方法的行为
-
father.study();
子类的对象赋值给父类的对象,调用引用变量的方法时,总是表现出子类对象方法的行为,这将出现,调用相同类型的变量的方法,表现出不同的特征,这就是多态!
那么多态和面向接口编程有什么关系呢?
假如,有个人需要用到自行车,但是某天他不需要自行车了,需要开轿车了。这时候我们不希望跑到自行车这个类里面去更改代码,因为别人还有可能用到这个自行车类。所以,我们就通过定义一个接口,然后通过多态来调用其子类(自行车类、轿车类)完成不同的任务!
下面通过代码来实现一下!
-
//car接口
-
public
interface Car {
-
public
void
userCar
();
-
}
-
-
//自行车类,实现car接口
-
public
class Bicycle implements Car {
-
public
void
userCar
() {
-
System.out.println(
"this is Bicycle");
-
}
-
}
-
-
//宝马车类,实现car接口
-
public
class BMW_Car implements Car{
-
public
void
userCar
() {
-
System.out.println(
"this is 宝马");
-
}
-
}
-
-
//person类用来调用car
-
public
class Person {
-
private Car car;
-
public
void
userCar
(){
-
car.userCar();
-
}
-
}
其注入关系实在Spring的配置文件中编写的
当我们不想骑自行车的时候,只需要在编写一个实现car接口的BWM_car即可,而不需要去修改自行车类。
一开始使用自行车类的时候,控制台输出:this is Bicycle
这个时候,怎么让 car.usrCar(); 这个方法的返回结果:this is 宝马
这时候,只需要修改配置,将BMW_car注入进去即可
如下:
-
<bean
id=
"person"
class=
"com.ahut.Person">
-
<
property
name
=
"car"
ref
=
"bicycle"
></
property
>
-
<
/bean>
将这种修改为下面这样就可以了:
-
<bean
id=
"person"
class=
"com.ahut.Person">
-
<
property
name
=
"car"
ref
=
"BMW_car"
></
property
>
-
<
/bean>
也就是相当于在Person类里面的声明由
private Car car = new Bicycle();
改为了
private Car car = new BMW_car();
没有这样写是因为Spring是通过配置文件来操作对象,这也是Spring的一大优点!
所以,我们只需要通过接口来调用方法,具体的实现类,我们不用担心,需要更改的时候,只需要去配置文件中修改一下新的实现类的地址即可!