日期:2014-05-20  浏览次数:20709 次

关于JAVA中继承的一些问题
最近在看Java的继承,大家都知道子类实例化的时候会把父类都实例化了。实例化后堆栈中只有一个子类对象,父类对象在堆中有没有具体对应的内存?我做了下面的实验跟踪了构造函数链,输出的结果全部是子类的对象。根据这个是不是可以理解继承只是把父类中的属性方法复制了一份在子类中,而没有具体的实例化出父类对象?  求高手指教
public class A {
public int num;

public A() {
System.out.println("A");
System.out.println("a-class" + this.getClass());
System.out.println("a-class" + super.getClass());
}

public A(int num) {
this.num = num;
System.out.println("a-class" + this.getClass());
System.out.println("a-class" + super.getClass());
System.out.println("a-num" + num);
}

public int sub(int n) {
return this.num + n;
}

@Override
public String toString() {
return "A [getClass()=" + this.getClass();
}

}
public class B extends A {
public int num;

public B() {
System.out.println("B");
System.out.println("b-class" + this.getClass());
System.out.println("b-class" + super.getClass());
}

public B(int num) {
super(num + 1);
this.num = num;
System.out.println("b-class" + this.getClass());
System.out.println("b-class" + super.getClass());
System.out.println("b-num" + num);
}

public int sub(int n) {
return super.num + n;
}

@Override
public String toString() {
return "B [getClass()=" + this.getClass();
}

}
public class C extends B {

public C() {
System.out.println("C");
System.out.println("c-class" + this.getClass());
System.out.println("c-class" + super.getClass());
}

public C(int num) {
super(num + 1);
System.out.println("c-num" + num);
System.out.println("c-class" + this.getClass());
System.out.println("c-class" + super.getClass());
}

public int sub(int n) {
return super.num + n;
}

@Override
public String toString() {
return "C [getClass()=" + this.getClass();
}

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

运行结果如下
A