开发者

Where do methods "live?"

If each object has a different copy of instance variables, where do methods "live?"

As an example:

class A {
    public foo() {
        System.out.println("foo");
    }
}

class B extends A {
    public foo() {
        System.out.println("foofoo");
    }
}

public class Main {
    public static void main(String[] args)开发者_运维百科 {
        A a = new B();
        a.foo(); // "foofoo"
    }
}

I know that "foofoo" is printed. So are the methods bound to the objects or something?


The process you are referring to is called dynamic dispatch. The way that this is typically implemented is through virtual tables (often called vtables):

http://en.wikipedia.org/wiki/Virtual_table

A simple summary of how vtables work is that each method is stored at some memory address, and a vtable stores those addresses. Using your example, A has a vtable with an entry that holds the memory address of its version of foo, while the subclass B has its own vtable with the same layout, but it instead holds the memory address of its own foo.


This is generally an implementation issue. All you need to concern yourself with as a Java programmer is that each class can have different methods from other classes.

In terms of implementation (if you're interested in under-the-covers behaviour), the easiest solution would be for each class to have a pointer to all the relevant functions.

That way, when you extend A with B, an instance of type B will get all of A's pointers to methods but with the foo method pointer pointing to B's code.

A graphical representation where B extends A, overriding just foo:

class A
    foo ----------> Afoo code
    bar ----+-----> Abar code
class B     |
    bar ----+
    foo ----------> Bfoo code

Instances of a class (objects) know about their type so you can get easily from object b to class B. From there, it's a simple operation to find the correct code to run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜