1

for example, lets say you have:

class X
{
    public void foo()
    {

    }

}

and then in your main you have

X anX = new X();
anX.foo();
X bX = new X();
bX.foo();

is the "foo" method being duplicated for every instance of X? Or is it that each instance just re-uses the foo method code.

1110101001
  • 4,662
  • 7
  • 26
  • 48
  • Each instance uses the same `foo` method at least that it is overridden in a subclass. – Luiggi Mendoza Jul 24 '13 at 01:51
  • 1
    Methods are shared among instances of the class. Each object just says "hey, I'm this object, invoke this method with respect to me." – ameed Jul 24 '13 at 01:53
  • 1
    So then the only difference between non-static methods and the static methods are that the static methods can be invoked without creation of an object. They are same in that there exists only one "master copy" of the method and that "master copy" is the only one used for everything. – 1110101001 Jul 24 '13 at 01:55
  • That "Master copy" is located in the __Perm Gen__ memory space of the JVM, see this already answered question: http://stackoverflow.com/questions/1262328/how-is-the-java-memory-pool-divided – morgano Jul 24 '13 at 01:57
  • Also, in the case of inheritance, upcasting + downcasting, and polymorphism, what happens when a derived object is created. Is is it similar to above where the new derived object just re-uses the existing base object method code? In the case of overriding the method in the derived class what happens? When upcasting the derived object into a base object what happens? – 1110101001 Jul 24 '13 at 02:00
  • I cannot think of a single case in Java where one would code a single method and have it turn somehow into multiple copies of that method. There's basically no mechanism in the Java class structure to duplicate methods. – Hot Licks Jul 24 '13 at 02:18

2 Answers2

1

It will reuse the method code for each object. What changes is the implicit argument, which is the object you invoke the method on.

tbodt
  • 16,609
  • 6
  • 58
  • 83
1

Instance methods are despatched (more or less) using a Class pointer and an internal virtual-method table. Similar, but slightly more indirect & slower, for methods accessed via an interface.

Class VMTs and method code are loaded once per ClassLoader & then shared between all objects using the method. Thus class type information & method code are not duplicated in memory.

Objects always keeps their Class pointer and the (internal) virtual-method table. This applies whether casting to a subtype or assigning to a supertype. Object Class and the internal pointer are assigned at construction and invariant for the lifetime of the object.

Static methods OTOH are not virtualized, do not use a VMT & despatch according to the static type of the reference. This is resolved at compile time.

Thomas W
  • 13,940
  • 4
  • 58
  • 76