当有疑问时,看看源代码(好吧,一个源代码;每个JVM都可以自由选择如何做到这一点,因为标准不要求任何内部表示)。所以我看了一下,并在JDK 7-u60的热点JVM的实现中发现了以下注释:
// A Klass is the part of the klassOop that provides:
// 1: language level class object (method dictionary etc.)
// 2: provide vm dispatch behavior for the object
// Both functions are combined into one C++ class. The toplevel class "Klass"
// implements purpose 1 whereas all subclasses provide extra virtual functions
// for purpose 2.
// One reason for the oop/klass dichotomy in the implementation is
// that we don't want a C++ vtbl pointer in every object. Thus,
// normal oops don't have any virtual functions. Instead, they
// forward all "virtual" functions to their klass, which does have
// a vtbl and does the C++ dispatch depending on the object's
我读它的方式是,这意味着,对于这个(非常流行的)实现,对象实例只存储一个指向其类的指针。具有更长或更短继承链的类的每个实例的成本实际上为 0。这些类本身确实占用了内存中的空间(但每个类只有一次)。深度继承链的运行时效率是另一回事。