如何存储实例方法 [英] How are instance methods stored

查看:151
本文介绍了如何存储实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

内存中的Java / C#方法表示

I想知道如果我在java中有一个对象,它是如何存储的实例方法?一个对象有没有指向它的实例方法?

I was wondering if i have an object in java, how are it's instance methods stored? Does an object have a pointer to it's instance methods?

示例:

public class MyObject {
 private int x;
 private int y;
 [..]
}

如果我计划很多(A这些 MyObject 在内存中,如果除了x的getter和yi定义一个实例方法之外,它将在内存方面产生重大的区别计算总和?

If i plan keeping a lot (A big tree of objects for example) of these MyObjects in memory, will it make a significant difference in memory terms if apart from a getter for x and for y i define an instance method calculating the sum?

我正在尝试整理,我应该添加更多的实例方法或使用getter和setter在另一个类中进行计算。

I'm trying to sort out wether i should add more instance methods or doing the calculations in another class using the getters and setters.

推荐答案

对象需要其属性的内存(注意:对于对象,存储的属性是指向真实对象的指针,位于内存的其他位置)。方法(代码)不需要额外的内存,因为它们与类一起存储。

The object needs memory for its attributes (NOTE: for object, the attribute stored is a pointer to the real object, which lies elsewhere in memory). No additional memory is needed for methods (code) as they are stored with the class.

IE:

public class MyClass1 {
  private int myNumber;
}

public class MyClass2 {
  private int myNumber;
  public int MyMethod1() {
  }
  public int MyMethod2() {
  }
  public int MyMethod3() {
  }
  ....
  public int MyMethod1000() {
  }
}

每个实例使用相同的内存。

use the same memory per instance.

这篇关于如何存储实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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