有一个Son类
package cn.extend;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
public class Son extends Father {
}
还有一个父类Father
package cn.extend;
public class Father {
private String name;
protected int age;
public Long maney;
private GrandFather grandFather;//这里是private私有成员
public GrandFather getGrandFather() {
return grandFather;
}
public final void setGrandFather(GrandFather grandFather) {
//这里声明final 子类不可以重写这个方法
this.grandFather = grandFather;
System.out.println("father final set Method---->"+this.grandFather.showFather());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getManey() {
return maney;
}
public void setManey(Long maney) {
this.maney = maney;
}
}
一个爷爷类GrandFather
package cn.extend;
public class GrandFather {
public String showFather() {
return "i am your father";
}
}
那么我们在spring的applicationContext.xml配置文件中
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
问题来了 我在Son的<bean 配置里面写上了父类所有的成员属性
而且我的setGrandFather()方法还是final的
测试类
public class TestExtends {
@Test
public void testExtend(){
ApplicationContext context=new ClassPathXmlApplicationContext("cn/extend/applicationContext.xml");
Father father=(Father)context.getBean("father");
Son son=(Son)context.getBean("son");
System.out.println(father.getAge()+father.getName());
System.out.println("father--->"+father.getGrandFather());
System.out.println(son.getAge()+son.getName());
System.out.println("son--->"+son.getGrandFather().showFather());
}
}
输出的结果
father final set Method---->i am your father(这句话说明父类的这个属性已经被赋值了)
0null(父类的属性也都是为空,但是神奇的是子类可以获得到)
father--->null(问题的是,为什么从容器中取出来的father调用getGrandFather()方法就是为null的呢)
22kenan
son--->i am your father(而且子类是可以获得父类的GrandParent()还可以拿出来,但是father类就是null,