Java - 我的意思是实例是否在内存中共享相同的实例方法?
例如:
public class Test {
private int a;
private int b;
public Test(int a , int b){
this.a = a;
this.b = b;
}
/* instance method - sum() */
public int sum(){
return a+b;
}
public static void man(String[] args) {
Test t1 = new Test(3,4);
Test t2 = new Test(5,6);
t1.sum();
t2.sum();
}
}
我知道当将 new
关键字应用于类时,类变量(属性)将被复制。因此实例可以单独拥有自己的属性值。
但是方法呢?它也会复制吗?如果是这样,只会浪费内存资源,因为方法总是相同的。
使用 new
关键字时 JVM 中发生了什么?非常感谢!
NOTE: official doc reference is highly preferred :)
最佳答案
But how about method? will it also make a copy? If so, just waste memory resources, because the methods are always same.
不,每个方法总会有一个副本(在 JVM 的方法区)。这适用于 static
和 non-static
方法。
Are there some kindly people tell me what happended in JVM when using a new keyword ? thanks very much!
简单地说,通过调用适当的构造函数在堆空间中创建一个new
对象。返回对该对象的引用。
关于Java - 创建多个实例时在内存中创建了多少个实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33407634/