在a类中创建b类的对象在C类中使用对象调用a的方法 对象怎么初始化

java 初始化跪求大神
2025-03-05 06:26:00
推荐回答(1个)
回答1:

这个很简单,写一下看看就知道了。

package Test.test;
/**
* 测试构造函数的调用顺序,为了能够看清楚顺序,所以每个类的构造函数中都写了一句输出
* @author mrzhou@miw.cn
* 2013-6-16 上午9:49:36
*/
public class Test {

public static void main(String[] args) {
new C();
}
static public class A {

public A() {
System.out.println("A inited");
}
}
static public class B extends A {

public B() {
super();
new D();//在B中初始化D
System.out.println("B inited");
}
}
static public class C extends B {

public C() {
super();
System.out.println("C inited.");
}
}
static public class D {

public D() {
System.out.println("D inited");
}
}

}
输出结果为:

A inited
D inited
B inited
C inited.
这就是顺序啦。