Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is information about methods of Java objects kept? [duplicate]

My colleague just asked me a really interesting question and I cannot give him an answer.

Let's assume that we have got the following class:

public class Person {
    String name;

    public Person(String name) {
        this.name = name;
    }

    public void print() {
        System.out.println("xxx");
    }
}

Now, we are creating the objects:

Person p1 = new Person("a");
Person p2 = new Person("b");
Person p3 = new Person("c");
Person p4 = new Person("d");
Person p5 = new Person("e");
Person p6 = new Person("f");
Person p7 = new Person("g");
Person p8 = new Person("h");

The question was:

Do we keep information about the available methods in each single object? If we create a new object p9, will the JVM create the object with information about only fields or will it also add to this object information about methods?

Another question:

What happens if I invoke p1.print()? Does p1 have to ask the Person class to provide this method, or is it already saved in p1 object?

like image 334
ruhungry Avatar asked Feb 04 '14 14:02

ruhungry


1 Answers

The code for methods isn't duplicated for all the instances, that would be completely unnecessary. The code lives in a special area in the memory, and it's shared by all the instances. The memory required by instance variables on the other hand naturally is owned by every instance.

As to how a method is called, the object doesn't really need to ask the class every time it calls a method, it has a pointer to the method's code and can just call it right away.

For more information on the inner workings of the JVM, refer here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html

like image 131
Kayaman Avatar answered Sep 24 '22 13:09

Kayaman