java中类的内存分配? [英] memory allocation for a class in java?

查看:127
本文介绍了java中类的内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

B类继承了A类。现在当我们创建一个B类型的对象时,为B分配的内存是多少?是包括A和B,还是内存分配的任何其他程序?

class B inherits class A. Now when we create an object of type B, what is the memory allocated for B? Is it including A and B, or any other procedure for memory allocation?

推荐答案

当你创建对象B时,让我们说调用默认构造函数

When you create the object B, let's say by calling the default constructor

B myObject = new B();

然后JVM分配一个或多或少的对象:

Then the JVM allocates an object with more or less:


  • B中显式声明的每个字段都有足够的内存(通常每个字段大约4-8个字节,但它与类型和主机系统有很大差异)

  • A及其祖先继承的每个最终字段都有足够的内存

  • 足够的内存包含对调度向量的引用(也应该在4-8字节左右)

编译器使用调度向量来存储可以在给定对象上调用的每个方法的地址,它取决于类对象本身而不是对象本身的实例(毕竟每个对象B都有相同的接口!)

The dispatch vector is used by the compiler to store the address of every method that can be invoked on the given object and it depends on the class of the object rather than the instance of the object itself (every object B has the same interface after all!)

所以你不需要分配A,因为没有单独的对象A.您没有实例化2个单独的对象。当你创建B时,你正在创建一个A的专用版本,它可以被视为一个更多的东西。所以只需要分配B(但请记住,B也有其祖先拥有的一切)

So you do NOT need to allocate A, because there's no separate object A. You aren't instancing 2 separate objects. When you create B you are creating a "specialized" version of A.. which it can be viewed as A with something more. So only B needs to be allocated (but keep in mind that B also has everything its ancestors have)

这篇关于java中类的内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆