Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How many instance-methods created in memory when create multiple instances?

Tags:

java

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 :)

like image 871
Eddy Avatar asked Jan 07 '23 06:01

Eddy


2 Answers

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.

like image 94
TheLostMind Avatar answered Jan 17 '23 14:01

TheLostMind


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.

like image 37
Pankaj Singh Avatar answered Jan 17 '23 15:01

Pankaj Singh