Reputation: 3723
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 :)
Upvotes: 4
Views: 1332
Reputation: 148
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.
Upvotes: 1
Reputation: 100269
Of course virtual calls make things somewhat more complex, but basically instance method is like a static method with additional implicit this
parameter. Calling t1.sum()
is like calling sum(t1)
(with additional null check for t1
). No reason to duplicate the method for every possible parameter value.
Upvotes: 0
Reputation: 622
All instances share the same code.
If you compile your Java class and create an instance inside of another class of it, they will call the function on the same Java class (.class)-File.
Upvotes: 0
Reputation: 36304
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.
Upvotes: 8