简体   繁体   中英

In a non-static method is the method duplicated every time an object is created?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM