1.C继承与B,
B继承与A,
A中含有C的引用
问题:
1.为什么A中的构造器中的this指代C对象
2.将A中构造器的this 赋值给A中的C类型变量c 会不会造成循环引用,请问这个要怎么理解?
代码如下
class A{
private String aName;
private C c;
public A(){
c = (C)this;
System.out.println("A"+this);
}
}
class B extends A{
private String bName;
public B(){
super();
System.out.println("B"+this);
}
}
class C extends B{
private String cName;
public C(){
}
}
main函数代码如下
public class Main {
public static void main(String[] args) {
C c = new C();
}
}
idea截图
这个问题源于spring源码中的ClassPathXmlApplicationContext 逐层调用父类,当进入AbstractApplicationContext中时,执行了这步
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
然后执行了
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
截图如下
这里的this 为什么指代的不是AbstractApplicationContext类,而是ClassPathXmlApplicationContext
会循环引用,c = (C)this;这么写会遇到运行错误,因为this是A不一定是C
在基础类引用派生类,这种写法,实际开发中没有用。讨论这种问题毫无意义。