简体   繁体   中英

How does java determine an object's actual type?

The question raises when I'm learning polymorphic conception in java. As the following code shows:

public class test {
    public static void main(String[] args){
        testF(new B());
    }
    public static void testF(A a){
        a.f();
    }
}
class A{
    public void f(){System.out.println("method in super class");}
}
class B extends A{
    public void f(){System.out.println("mehtod in sub class");}
}

testF method requires a class A parameter, but we pass a class B reference, which is the subclass of A class. The compile is glad to accept it, and because the polymorphism mechanism, when we invoke the method f() on the reference 'a', the method that declared in the "actual type" will get. My question is that, when we pass a new build object B to testF(), it has been upcast to class A, so how could java then get its actual type?

Java keeps a virtual method table (AKA dispatch table) with each object so it knows which f to actually call when it gets called at runtime.

It also keeps track of related meta-ish information about the objects like what class they are an instance of ... etc.

Note that doesn't actually up cast in the sense that you are thinking. The runtime does a minimal amount of safety/type checking, but outside of that it uses the virtual method table to lookup which method to run when it gets called.

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