Java - I mean do instances share same instance method in memory?
For example:
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();
}
}
I know when apply new
keyword to a class, class variables (properties) will be copied. So instances can have their own property values separately.
But how about method? will it also make a copy? If so, just waste memory resources, because the methods are always same.
what happended in JVM when using a new
keyword ? thanks very much!
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.
No, there will always be a single copy of each method (in the method area of the JVM). This applies for both static
and non-static
methods.
Are there some kindly people tell me what happended in JVM when using a new keyword ? thanks very much!
Simply put, a new
Object is created in the heap space by calling the appropriate constructor. A reference to that object is returned.
Methods of a class is stored on stack in .class instance which stores all methods of a class. Only one copy is created for method and it is invoked by all instance of the class.JVM keeps reference of all methods defined in a class and linked it with instance when it calls a method.
what happended in JVM when using a new keyword ?
When we simply put 'new' keyword it creates an object on the heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With