子类实例化时会先构造一个父类的对象,然后才构造子类对象,那么这个子类对象是否是在父类对象的基础上构造的,即内存映像上是叠加的?如果不是,那么这个父类对象构造后干什么用了?这个子类对象难道是完全重新构造吗?如果是,那么子类对象就应该具有父类的所有域和方法了,包括父类私有的成员(只是不能访问而已)?请说明机理。

解决方案 »

  1.   

    我在jvm中给你找到了下面的说明,希望对你理解这一问题有所帮助。
    Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely created.
    对于你的问题,可以从中找到答案,在产生子类对象时候,先将父类的所有变量进行初使化,不管他后面将用到还是不用到,所有变量都会会分配内存,直到内存溢出。注意并没有产生一个什么父类对象,第二段举了一个列子,如果你用了覆盖,尽管父类的那个方法不再使用,便他依然被产生了。