开发者

How is it inheritance different from association when it comes to memory layout

I have a ba开发者_运维知识库sic question, How is inheritance different from association when it comes to memory layout.

class BaseClass{
 private int i;
 public void DoSomethinG(){} 
}

class DerivedClass : BaseClass{
}

class AssocClass {
private BaseClass bClass = new BaseClass();
}

Other than access restriction to private members ,I believe both DerivedClass and AssocClass are same. Memory for variable i in BaseClass is allocated in both the cases the size of DerivedClass and AssocClasss should be same.

Am I right in my assumption or am I missing something trivial ?

Regards, Jeez


Memory layout is different between the two. With DerivedClass the data from both DerivedClass and BaseClass will be stored together. You can't have an instance of DerivedClass without also having an implicit instance of BaseClass.

AssocClass has a reference to an instance of BaseClass. This could be null so there may be no instance at all. If there is an instance, it is a separate object that is stored somewhere else. E.g. it could be in a different generation of the heap. This also means that the instances could be garbage collected independently (provided of course that the instance of AssocClass doesn't reference the instance of BaseClass).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜