首先定义一个父亲类
@Data
public class fatherN {
private String surname;
private String sex;
private int age;
}
定义一个孩子类
@Data
public class childrenN {
private String surname;
private String sex;
private int age;
}
根据传统,一般情况下孩子是跟随父亲姓的,所以我们可以在Beans.xml文件中去定义一个父亲类,然后让这个孩子去继承这个父亲,可以看到我们在配置文件中,并没有给孩子的姓氏去复制,而是让其直接去继承了父类。
<bean id="Father" class="com.LL.sp2.fatherN">
<property name="surname" value="王"></property>
<property name="sex" value="男"></property>
<property name="age" value="56"></property>
</bean>
<bean id="Children" class="com.LL.sp2.childrenN" parent="Father">
<property name="sex" value="女"></property>
<property name="age" value="5"></property>
</bean>
输出一下
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Bean.xml");
fatherN father = (fatherN) context.getBean("Father");
childrenN children = (childrenN) context.getBean("Children");
System.out.println(father);
System.out.println(children);
}
我们可以看到,孩子也确实姓王!说明闺女是老王亲生的!
老王的祖先,老老王来了,可惜他已经不在世了,所以我们并不能去new一个老老王,那怎么办呢?
老老王的后代不出意外的话都是姓王,所以我们在配置文件中声明的一个没见过的抽象老老王,然后让他的子孙后代都去继承他。
<bean id="ancestors_wang" abstract="true">
<property name="surname" value="王"></property>
<property name="sex" value="男"></property>
</bean>
<bean id="Children" class="com.LL.sp2.childrenN" parent="ancestors_wang">
<property name="sex" value="女"></property>
<property name="age" value="5"></property>
</bean>
从上面的代码中,我们就抽象出一个去世的老老王!输出一下,看一下关系。
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Bean.xml");
childrenN children = (childrenN) context.getBean("Children");
System.out.println(children);
}
我们可以看到,孩子确实继承了老老王的姓氏!
补充一下:老老王已经去世,属于抽象类,所以我们并不能去获取一个老老王对象!